设置背景绘制对象与各国的Andr​​oid按键按键、对象、背景、Andr

2023-09-06 15:01:17 作者:莫让浮云遮望眼

我建立一个选择题问卷Android程序。我在onCreate()方法如下

I am building a multiple choice questionnaire android program. I have the following in my onCreate() method

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定义了一个红色的颜色渐变为pressed状态,灰色的其他国家。它看起来如下:

The drawable resource "optionbutton.xml" defines a red colour gradient for the "pressed state", and a grey for other states. It looks as follows

<?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 pressed,最后(不是那个pressed)按钮仅获得其背景为红色。

The selector actually works, but on the last applied button only. No matter which button from the 5 is pressed, the last (not the one pressed) button only gets its background red.

随着调试的步骤:我想展开for循环,改变应用背景的顺序,最后应用按钮,只得到红色背景:

As a debugging step: I tried to unroll the for-loop and change order of applying the background, the last applied button only gets red background:

((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

这是令人困惑!这有什么错我的执行?

This is confusing! What's wrong with my implementation?

推荐答案

这似乎 setBackgroundDrawable() 是德precated。您可以像使用其他替代的 setBackgroundResource()

It seems setBackgroundDrawable() is deprecated. You can use another alternative like setBackgroundResource().