用字符串从R中取一个id

时间:2013-06-14 14:02:40

标签: java android xml android-resources

我有一个带有一些按钮的表和TextView(称为Row2Col1,Row2Col3,Row2Col4),我想从一个字母生成的字符串中获取它们的id。代码是:

String index = "Row" + (currentRow + 2) + "Col1";
    Button buttonTable = (Button) findViewById(getResources()
            .getIdentifier(index, "id", getPackageName()));
    buttonTable.setVisibility(0);

    index = "Row" + (currentRow + 2) + "Col3";
    TextView textViewBrand = new TextView(getApplicationContext());
    textViewBrand = (TextView) findViewById(getResources().getIdentifier(
            index, "id", getPackageName()));
    textViewBrand.setText(brand);

    index = "Row" + (currentRow + 2) + "Col4";
    TextView textViewTread = new TextView(getApplicationContext());
    textViewTread = (TextView) findViewById(getResources().getIdentifier(
            index, "id", getPackageName()));
    textViewTread.setText(tread);

程序在第二行崩溃,其中是findViewById。有什么想法吗?

1 个答案:

答案 0 :(得分:2)

根据您的错误文本,您在xml中有TextView,但是您尝试将其转换为代码中的Button。将您的代码更改为

String index = "Row" + (currentRow + 2) + "Col1";
    TextView buttonTable = (TextView) findViewById(getResources()
            .getIdentifier(index, "id", getPackageName()));
    buttonTable.setVisibility(0);

它会起作用。