1

私はこれを持っています:

// Set up touch listeners for all the buttons
    View cardButton = findViewById(R.id.C_0);
    cardButton.setTag(0);
    cardButton.setOnTouchListener(this);
    View cardButton1 = findViewById(R.id.C_1);
    cardButton1.setTag(1);
    cardButton1.setOnTouchListener(this);
    View cardButton2 = findViewById(R.id.C_2);
    cardButton2.setTag(2);
    cardButton2.setOnTouchListener(this);
    View cardButton3 = findViewById(R.id.C_3);
    cardButton3.setTag(3);
    cardButton3.setOnTouchListener(this);
    View cardButton4 = findViewById(R.id.C_4);
    cardButton4.setTag(4);
    cardButton4.setOnTouchListener(this);
    View cardButton5 = findViewById(R.id.C_5);
    cardButton5.setTag(5);
    cardButton5.setOnTouchListener(this);
    View cardButton6 = findViewById(R.id.C_6);
    cardButton6.setTag(6);
    cardButton6.setOnTouchListener(this);
    View cardButton7 = findViewById(R.id.C_7);
    cardButton7.setTag(7);
    cardButton7.setOnTouchListener(this);
    View cardButton8 = findViewById(R.id.C_8);
    cardButton8.setTag(8);
    cardButton8.setOnTouchListener(this);

しかし、プログラムで生成する必要があるため、このように書き出すことはできません。残念ながら、私は 3 つの方法を試しましたが、うまくいきませんでした。まず:

for(int i = 0; i < 9; i++)
    {
        String bufferName = "C_" + i;
        int tempid = getResources().getIdentifier(bufferName, "drawable", getPackageName());
        View cardButton = findViewById(tempid);
        cardButton.setTag(i);
        cardButton.setOnTouchListener(this);
    }

これにより、NullPointerException が発生します。それを特定する方法がわかりません。また、アンドロイドのことは、とにかく高価なので getIdentifier を使用すべきではないと言っています。

次の試行:

ViewGroup rootLayout=(ViewGroup) sv.getRootView();
    View v;
    int id = 0;
    for(int i = 0; i < rootLayout.getChildCount(); i++) {
        v = rootLayout.getChildAt(i);
        if(v instanceof View)
        {
            v.setTag(id);
            id += 1;
            v.setOnTouchListener(this);
        };
    }

ここにエラーはありませんが、ボタンはもう機能しません。リスナーが設定されていないか、タッチが適切に録音されていないか、その他のいずれかです。

3 回目の試行:

int[] ids = {R.id.C_0, R.id.C_1, R.id.C_2, R.id.C_3, R.id.C_4, R.id.C_5, R.id.C_6, R.id.C_7, R.id.C_8};
    for (int id:ids)
    {
        ImageView b = (ImageView)findViewById(id);
        b.setTag(ids);
        b.setOnTouchListener(this);
    }

これは最悪の方法であり、使用したくありませんが、これでもうまくいきません。ClassCastException を取得していました。使用してみImageButton b = (ImageButton)findViewById(id);ましたが、それでも同じエラーが発生しました。これがまったく新しいものである場合は申し訳ありませんが、これを行う方法を見つけようと何時間も費やしました. :(

4

1 に答える 1

0

最初に:
最初の試みは非常に近いです...ここで間違ったタイプを使用しています:

int tempid = getResources().getIdentifier(bufferName, "drawable", getPackageName());

あなたはid、使用したい:

int tempid = getResources().getIdentifier(bufferName, "id", getPackageName());

次の試行:
これは問題ないようです。エラーが発生したのは OnTouchListener である可能性があります。


3 番目の試行:
ClassCastException は、XML で宣言した View 型が何であれ、Java コードで使用する View 型のクラスでなければならないことを意味します...

于 2013-01-04T06:58:55.390 に答える