我有很多 1 个按钮的代码。有什么方法可以缩短这段代码。
pic1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
pic1.setTag("beck");
if (pic2.getTag()==("beck")){
new CountDownTimer(500,500) {
public void onTick(long millisUntilFinished) {}
public void onFinish() {
player=MediaPlayer.create(MainActivity.this,R.raw.correct);
player.start();
pic1.setVisibility(View.INVISIBLE);
pic2.setVisibility(View.INVISIBLE);
}}.start();
}
if (pic1.getTag()==("beck")){pic1.setBackgroundResource(R.drawable.becks);}
if (pic3.getTag()==("rob") || pic4.getTag()==("rob")
||pic5.getTag()==("shan") || pic6.getTag()==("shan")
||pic7.getTag()==("mel") || pic8.getTag()==("mel")
||pic9.getTag()==("dumm") || pic10.getTag()==("dumm")
||pic11.getTag()==("jboot") || pic12.getTag()==("jboot") ) {
pic1.setTag ("boot");pic1.setBackgroundResource(R.drawable.jordboots);
pic2.setTag ("boot");pic2.setBackgroundResource(R.drawable.jordboots);
pic3.setTag ("boot");pic3.setBackgroundResource(R.drawable.jordboots);
pic4.setTag ("boot");pic4.setBackgroundResource(R.drawable.jordboots);
pic5.setTag ("boot");pic5.setBackgroundResource(R.drawable.jordboots);
pic6.setTag ("boot");pic6.setBackgroundResource(R.drawable.jordboots);
pic7.setTag ("boot");pic7.setBackgroundResource(R.drawable.jordboots);
pic8.setTag ("boot");pic8.setBackgroundResource(R.drawable.jordboots);
pic9.setTag ("boot");pic9.setBackgroundResource(R.drawable.jordboots);
pic10.setTag ("boot");pic10.setBackgroundResource(R.drawable.jordboots);
pic11.setTag ("boot");pic11.setBackgroundResource(R.drawable.jordboots);
pic12.setTag ("boot");pic12.setBackgroundResource(R.drawable.jordboots); }
}});
例如,创建第二个类来保存代码,以便我可以在需要时调用它。或诸如此类的方法
pic1,pic2,pic3.setTag("boot")
我创建了第二个类,并将标签和背景重置放入其中。
public class resetbuttons extends MainActivity{
public void buttreset () {
pic1.setTag("boot");
pic1.setBackgroundResource(R.drawable.jordboots);
pic2.setTag("boot");
pic2.setBackgroundResource(R.drawable.jordboots);
// etc etc for 12 buttons }}
并用它代替 if 语句标签和图像代码。
resetbuttons parent = new resetbuttons();
parent.buttreset();
所有代码看起来都很干净,但是当我在调用 buttreset 后立即运行它时,应用程序崩溃了。我需要在 list 或 xml 代码中添加任何内容吗?如果不是我的错误在哪里。这是我想在主要 Activity 中摆脱的主要代码
最佳答案
使用带有for-loop
的数组/集合来一次又一次地执行相同的操作:
View[] views = {pic1, pic2, pic3, pic4, pic5, pic6, pic7, pic8, pic9, pic10, pic11, pic12};
for(View v : views){
v.setTag("boot");
v.setBackgroundResource(R.drawable.jordboots);
}
此外,如果要比较 String
对象,则需要将所有 ==
更改为 equals()
。
关于java - 是否可以缩短批量代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19772334/