android - 无法以编程方式选择 tableRow 的子项(textview)

标签 android casting textview android-tablelayout

我正在尝试使用 TableLayout#getChildAt(i).getChildAt(j) 打印 TableRows 内的 TextViews 的值。

当我尝试使用上面的方法记录它时,logcat 提示说它是一个 View 对象并且它没有我正在尝试使用的方法 (getText())。

TableRow 中唯一的 View 是 TextView。

// List<TextView> textViewBoxes...

private void createViews() {
    ...

    tblLayout = new TableLayout(this);
    tblRow01 = new TableRow(this);
    ...

    for (int i = 0; i < 99; i++) {
        TextView text = new TextView(this);
        text.setText("Player " + i);
        textViewBoxes.add(text);
    }

    tblRow01.addView(textViewBoxes.get(0));
    ...

    tblLayout.addView(tblRow01);
    ...

    // Print the contents of the first row's first TextView
    Log.d(TAG, ("row1_tv1: " +
            tblLayout.getChildAt(0).getChildAt(0).getText().toString));

    ...
}

最佳答案

你试过这样的事情吗?

TableRow row = (TableRow)tblLayout.getChildAt(0);
TextView textView = (TextView)row.getChildAt(XXX);
// blah blah textView.getText();

你也可以一行完成,但它有时看起来很丑:

// wtf?
((TextView)((TableRow)tblLayout.getChildAt(0)).getChildAt(XXX)).getText();

无论如何...您在这里所做的是将 View 转换为您想要的特定类型。您可以毫无问题地这样做,因为您完全确定每个 TableLayout 的 子级都是一个 TableRow,并且您知道 TableRow 的 子级位于 XXX 位置是一个 TextView

关于android - 无法以编程方式选择 tableRow 的子项(textview),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4079164/

相关文章:

android - 如何显示启用位置对话框,如谷歌地图?

java - org.json.JSONArray 类型的值无法转换为 JSONObject

android - 在 Android Studio 中用 Kotlin 自动生成 getter 和 setter

c - uint8 的冗余转换不适用于 GCC 4.8.1

android - 将文本和图像彼此完美对齐

android - ViewPager 特定版本中的 Settext 问题 - 5.1.1 android?

Android - AsyncTask 的问题

java - 我们究竟需要如何使用类型转换?

数据库服务器。为什么 [几乎] 任何类型的字段值都可以在查询/DML 中被视为带引号的字符串?

android - 使用relativelayout让textview占据屏幕一半的宽度