私は多肢選択式のアンケート Android プログラムを構築しています。onCreate() メソッドに次のものがあります
btnArray = new Button[5];
btnArray[0] = (Button) findViewById(R.id.bOp1);
btnArray[1] = (Button) findViewById(R.id.bOp2);
btnArray[2] = (Button) findViewById(R.id.bOp3);
btnArray[3] = (Button) findViewById(R.id.bOp4);
btnArray[4] = (Button) findViewById(R.id.bOp5);
Typeface othmanyFont = Typeface.createFromAsset(getAssets(),
"fonts/amiri.ttf");
Drawable shape = getResources().getDrawable(R.drawable.optionbutton);
for(int i=0;i<5;i++){
btnArray[i].setTypeface(myFont);
((Button)btnArray[i]).setBackgroundDrawable(shape); //Button-4 only turns red
btnArray[i].setOnClickListener(this);
}
ドローアブル リソース "optionbutton.xml" は、"押された状態" に対して赤色のグラデーションを定義し、その他の状態に対して灰色を定義します。次のようになります
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" >
<shape>
<gradient
android:startColor="#bf1d00"
android:endColor="#801300"
android:angle="270" />
<corners android:radius="10dp" />
<stroke
android:width="1dp"
android:color="#71c2eb" />
</shape>
</item>
<item>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient android:startColor="#FFFFFF"
android:endColor="#999"
android:angle="270" />
<corners android:radius="10dp" />
<stroke android:width="1px" android:color="#0070b7" />
</shape>
</item>
</selector>
セレクターは実際には機能しますが、最後に適用されたボタンでのみ機能します。5 のどのボタンが押されても、最後の (押されたボタンではない) ボタンの背景は赤になります。
デバッグ手順として: for ループを展開し、背景を適用する順序を変更しようとしましたが、最後に適用されたボタンは赤い背景のみを取得します。
((Button)btnArray[0]).setBackgroundDrawable(shape);
((Button)btnArray[1]).setBackgroundDrawable(shape);
((Button)btnArray[2]).setBackgroundDrawable(shape);
((Button)btnArray[4]).setBackgroundDrawable(shape);
((Button)btnArray[3]).setBackgroundDrawable(shape); //Button-3 only turns red
これは紛らわしいです!私の実装の何が問題になっていますか?