我正在开发一个示例游戏应用程序,其中我需要随机更改四个按钮图像。因为,我正在使用以下逻辑。但是,我无法更改开关盒中的按钮背景。所以,请指导我在哪里出错。谢谢你。
xml布局
<LinearLayout
android:layout_height="match_parent"
android:layout_width="fill_parent"
android:orientation="horizontal"
android:gravity="center"
>
<Button
android:id="@+id/b1"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:background="@drawable/white"
/>
<Button
android:id="@+id/b2"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:background="@drawable/white"
/>
<Button
android:id="@+id/b3"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:background="@drawable/white"
/>
<Button
android:id="@+id/b4"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:background="@drawable/white"
/>
</LinearLayout>
java类
public class MainActivity extends Activity implements OnClickListener {
private Button b1,b2,b3,b4;
ArrayList<Integer> numbers = new ArrayList<Integer>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1=(Button)findViewById(R.id.b1);
b2=(Button)findViewById(R.id.b2);
b3=(Button)findViewById(R.id.b3);
b4=(Button)findViewById(R.id.b4);
b1.setOnClickListener(this);
b2.setOnClickListener(this);
b3.setOnClickListener(this);
b4.setOnClickListener(this);
//random numbers are 0,1,2,3
Random randomGenerator = new Random();
while (numbers.size() < 4) {
int random = randomGenerator .nextInt(4);
if (!numbers.contains(random)) {
numbers.add(random);
}
}
startScan();
}
public void startScan() {
new Thread() {
public void run() {
for(int i=0;i<numbers.size();i++){
try{
Thread.sleep(3000);
int id=numbers.get(i);
alterImages(id);
}catch(Exception e){
}
}
}
}.start();
}
private void alterImages(int id) {
// TODO Auto-generated method stub
Log.e("id value is in switch case",""+id);
switch(id)
{
case 0: {
b1.setBackgroundResource(R.drawable.green); //its not working
Log.e("id is....","case 0"); // its is printing
break;
}
case 1: {
b2.setBackgroundResource(R.drawable.blue);
Log.e("id is....","case 1");
break;
}
case 2 :
{
b3.setBackgroundResource(R.drawable.red);
Log.e("id is....","case 2");
break;
}
default :
b4.setBackgroundResource(R.drawable.yellow);
Log.e("id is....","DEFAULT");
break;
}
}