質問

Androidアプリケーションを作成しています。ここでは、数百のボタンで構成されるビューがあり、それぞれに特定のコールバックがあります。ここで、何百行のコード(ボタンごとに)を記述する代わりに、ループを使用してこれらのコールバックを設定したいと思います。

私の質問は、各ボタンIDを静的に入力する必要なく、findViewByIDを使用するにはどうすればよいですか?これが私がやりたいことです:

    for(int i=0; i<some_value; i++) {
       for(int j=0; j<some_other_value; j++) {
        String buttonID = "btn" + i + "-" + j;
        buttons[i][j] = ((Button) findViewById(R.id.buttonID));
        buttons[i][j].setOnClickListener(this);
       }
    }

前もって感謝します!

役に立ちましたか?

解決

使用する必要があります getIdentifier()

for(int i=0; i<some_value; i++) {
   for(int j=0; j<some_other_value; j++) {
    String buttonID = "btn" + i + "-" + j;
    int resID = getResources().getIdentifier(buttonID, "id", getPackageName());
    buttons[i][j] = ((Button) findViewById(resID));
    buttons[i][j].setOnClickListener(this);
   }
}

他のヒント

すべてのボタンIDを保持しているINT []を作成してから、次のことを繰り返すことができます。

int[] buttonIDs = new int[] {R.id.button1ID, R.id.button2ID, R.id.button3ID, ... }

for(int i=0; i<buttonIDs.length; i++) {
    Button b = (Button) findViewById(buttonIDs[i]);
    b.setOnClickListener(this);
}

アクセスする場合は、タグを使用できます。

onClick

int i=Integer.parseInt(v.getTag);

しかし、このようなボタンにアクセスすることはできません。

プログラムでボタンを作成するだけです

Button b=new Button(this);

以下に示したように、XMLでむしろJavaコードでカスタムボタンを作成します

Button bs_text[]= new Button[some_value];

    for(int z=0;z<some_value;z++)
        {
            try
            {

            bs_text[z]   =  (Button) new Button(this);

            }
            catch(ArrayIndexOutOfBoundsException e)
            {
                Log.d("ArrayIndexOutOfBoundsException",e.toString());
            }
        }

あなたのトップレベルビューが子供としてそれらのボタンビューしか持っていない場合、あなたはできます

for (int i = 0 ; i < yourView.getChildCount(); i++) {
    Button b = (Button) yourView.getChildAt(i);
    b.setOnClickListener(xxxx);
}

さらにビューがある場合は、選択したビューがボタンの1つであるかどうかを確認する必要があります。

何らかの理由で使用できない場合 getIdentifier() 機能および/または可能なIDを事前に知っている場合、スイッチを使用できます。

int id = 0;

switch(name) {
    case "x":
        id = R.id.x;
        break;
    etc.etc.
}

String value = findViewById(id);
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top