search

Home  >  Q&A  >  body text

android-studio - android中动态添加点击方法时调用类变量的问题

我在前面定义了一个类变量
public int arrBomb[][] = new int10;

然后给一个动态添加的按钮,绑定了点击方法
Button btn = new Button(this);
btn.setBackgroundResource(R.drawable.bg);
btn.setTag(R.id.row,row);
btn.setTag(R.id.col,col);
//点击事件
btn.setOnClickListener(clickListener);
grid.addView(btn, params);

接着,发现在clickListener方法里使用不了arrBomb这个变量,请问是怎么回事呢?
public View.OnClickListener clickListener = new View.OnClickListener() {

    public void onClick(View v) {
        GridLayout grid = (GridLayout)findViewById(R.id.main);
        Button btn = (Button)v;
        int row = (int)btn.getTag(R.id.row);
        int col = (int)btn.getTag(R.id.col);
        grid.removeView(btn);
        Log.d("AAA",row + "===" + col);
    }
};

应该要如何使用呢?谢谢,本人是安卓菜鸟。

迷茫迷茫2772 days ago420

reply all(1)I'll reply

  • 阿神

    阿神2017-04-18 09:07:13

    As long as arrBomb and clickListener are declared in the same class, arrBomb can be referenced in onClick(), so I don’t know your specific writing method and context.
    tips:

    1. When declaring a two-dimensional array in Java, int[][] are usually connected together.

    2. int[][] arrBomb = new int[10][];

    3. You can directly use Activity or Fragment to implement the View.onClickListener interface. There is no need to declare a variable.

    reply
    0
  • Cancelreply