如何使用getResources()。getIdentifier来获取Button id?

时间:2017-01-21 23:12:28

标签: android android-arrayadapter

我正在尝试制作一个简单的应用程序 我有一张桌子,那一行有一排七个按钮 我知道我不需要2D阵列,但我想用它 所以我可以很容易地扩展它。

我正在使用

int resID = getResources().getIdentifier("button" + i + h, "button", getPackageName());

尝试从Button获取资源ID 我的按钮被命名为" button00,button01,button02等(这正是R.java中的确切方式)。
数字分别代表行和列。 我以前见过人们使用过它,但由于某种原因,我永远无法使用它。

这是我的灯类代码

public class lights extends Activity implements OnClickListener {
public int numRows;
public int numCol;


public lights(int rows, int col) {
    numRows = rows;
    numCol = col;
}


public void createButtonListeners(Button[][] button) {
    for (int i = 0; i < numRows; i++) {
        for (int h = 0; h < numCol; h++) {
            int resID = getResources().getIdentifier("button" + i + h, "button", getPackageName());
            button[i][h] = (Button) findViewById(resID);
            button[i][h].setOnClickListener((View.OnClickListener) this);
            Toast.makeText(getBaseContext(), "Made listener", Toast.LENGTH_LONG).show();
        }
    }
}


public void reset(Array buttons[][]) {
    for (int r = 0; r < numRows; r++) {
        for (int c = 0; c < numCol; c++) {

            //havnt got this far
        }

    }

}


public int wasButtonPressed() {
    for (int row = 0; row < numRows; row++) {


    }

    return 0;
}

@Override
public void onClick(DialogInterface dialog, int which) {

}}

Main_Activity代码

public class MainActivity extends Activity implements View.OnClickListener {

lights mlights = new lights(1, 7);
Button Button[][] = new Button[mlights.numRows][mlights.numCol];


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mlights.createButtonListeners(Button);

}


@Override
public void onClick(View v) {

}}

当我输入我的代码但没有运行时,我没有错误 请以任何可能的方式纠正我

1 个答案:

答案 0 :(得分:1)

如果你想获得一个id,第二个参数应该是"id"

您尝试获取R.id值,而不是R.button值,因为那些不存在

你还在你的灯光活动上实现了错误的点击监听器(不管怎么说都不应该扩展活动,但这与你的问题无关......如果你当前的代码没有&#39,请不要感到惊讶;工作)

提示:尝试使用此public lights(Context c, int rows, int col)并使用c.getResources使用Context来创建您的资源,或者可能使用setButtons(Button[][] buttons)方法从活动中调用(因为那是你可以拨打findViewById

的唯一地方