1

次のようなテーブルが作成されています。

    TableLayout layout = new TableLayout(this);
    layout.setLayoutParams(new TableLayout.LayoutParams(4,5));
    layout.setPadding(1, 1, 1, 1);

    for(int i=0; i<7; i++) {
        TableRow tr = new TableRow(this);
        for(int j=0; j<6; j++) {
            Button b = new Button(this);
            b.setText("0");
            b.setOnClickListener(buttonListener);
            tr.addView(b);
        }
        layout.addView(tr);
    }

    super.setContentView(layout);

OnClickListener buttonListener

View.OnClickListener buttonListener = new View.OnClickListener() {
    public void onClick(View v) {
        Button thisButton = (Button) findViewById(((Button)v).getId());
        //thisButton.setText(Integer.toString(Integer.parseInt((String) thisButton.getText()) + 1));
        thisButton.getText();
    }
};

への呼び出しthisButton.getText()は NullPointerException をスローしますが、その理由はわかりません。誰でも私を助けることができますか?

4

5 に答える 5

0
    TableLayout layout = new TableLayout(this);
            layout.setLayoutParams(new TableLayout.LayoutParams(4,5));
            layout.setPadding(1, 1, 1, 1);

            for(int i=0; i<7; i++) {
                TableRow tr = new TableRow(this);
                for(int j=0; j<6; j++) {
                    Button b = new Button(this);
                    b.setText("0");
                    b.setOnClickListener(buttonListener);
                    tr.addView(b);
                }
                layout.addView(tr);
            }

            setContentView(layout);
}
     View.OnClickListener buttonListener = new View.OnClickListener() {
                public void onClick(View v) {
                    Button btn1 = (Button)v;
                    //thisButton.setText(Integer.toString(Integer.parseInt((String) thisButton.getText()) + 1));
                    String name = btn1.getText().toString();                    
                }
            };

私はこれが動作することをテストしました。ビューを動的に作成する場合、ID を割り当てる必要はありません。ビューのオブジェクトを使用して作業します。動的ボタンに id を設定することに興味があるすべての人にとって、それが理にかなっていることを願っています。

于 2012-10-09T06:17:47.997 に答える
-1

コードに 1 つの問題があります。

ボタンのIDを設定していません

        b.setText("0");
        b.setOnClickListener(buttonListener);
        b.setId(i);
于 2012-10-09T05:37:28.047 に答える
-1

ボタンを再作成する代わりに、渡されたビューからテキストを取得するだけです。

public void onClick(View v) {
    if(v instanceof Button)
        String text = ((Button) v).getText();
}
于 2012-10-09T05:29:24.797 に答える
-1

予測:

  1. ボタンにIDを設定することに関して何も見えません
  2. 以下の行は例外を引き起こす可能性があります:

ボタン thisButton = (ボタン) findViewById(((ボタン)v).getId());

なんでやってんの?代わりに、クリック アクションで既にビューを渡しています。View v

したがって、次のように直接行うことができます。

String strText = ((Button) v).getText();
于 2012-10-09T05:30:07.860 に答える
-1

その前のステートメントが成功しなかったため、 thisButton がおそらく null であることを意味します。

ボタン thisButton = (ボタン) findViewById(((ボタン)v).getId());

正しく見えません。通常、findViewById() 内のパラメーターはリソース ID である必要があります。そのような

ボタン thisButton = (ボタン) findViewById(R.id.button);

R.id.button は、レイアウト xml によって定義されます。

于 2012-10-09T05:31:52.020 に答える