我想随机显示5个xml布局,并且我也会点击相应的按钮,每个都出现xml文件。以下代码工作得非常棒.---- ** 我已经在xml文件的每次shuffle上放了0.75秒的延迟。在这个延迟中我有一个声音可以播放。我没有真的想法如何实现这一点。在下面的代码中我使用了Switch-Case,但它无法正常工作。我的要求是如果我点击xml file1上的Button,我想播放Sound1,如果Button来自Xml文件5 ,我想播放相应的Sound5等等......就像那样0.75秒并移动到下一个XML文件并重复循环。 * ----
public class ReceivingActivity extends Activity{
Random random = new Random();
Handler handler = new Handler();
private int mPosition = 0;
private Handler mHandler = new Handler();
private List<Integer> mLayouts;
private Button mButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
mLayouts = new ArrayList<Integer>();
mLayouts.add(R.layout.first);
mLayouts.add(R.layout.second);
mLayouts.add(R.layout.third);
mLayouts.add(R.layout.fourth);
mLayouts.add(R.layout.fifth);
Collections.shuffle(mLayouts);
setContentView(mLayouts.get(mPosition));
mButton = (Button)findViewById(R.id.btnid);
mButton.setOnClickListener(mListener);
mPosition++;
}
private OnClickListener mListener = new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(), "WTH is happening", Toast.LENGTH_SHORT).show();
// TODO Auto-generated method stub
if(mPosition >= mLayouts.size()){
int lastId = mLayouts.get(mLayouts.size() - 1);
Collections.shuffle(mLayouts);
while (lastId == mLayouts.get(0)) {
Collections.shuffle(mLayouts);
}
mPosition = 0;
}
setContentView(mLayouts.get(mPosition));
switch (mLayouts.get(mPosition)) {
case R.layout.first:
Toast.makeText(getApplicationContext(), "First", Toast.LENGTH_SHORT).show();
iv1.setBackgroundResource(R.drawable.ic_launcher);
break;
case R.layout.second:
Toast.makeText(getApplicationContext(), "second", Toast.LENGTH_SHORT).show();
//Some sound
iv2.setBackgroundResource(R.drawable.ic_launcher);
break;
case R.layout.third:
Toast.makeText(getApplicationContext(), "third", Toast.LENGTH_SHORT).show();
//Some media , Different for each Layout..
iv3.setBackgroundResource(R.drawable.ic_launcher);
break;
case R.layout.fourth:
Toast.makeText(getApplicationContext(), "fourth", Toast.LENGTH_SHORT).show();
iv4.setBackgroundResource(R.drawable.ic_launcher);
break;
case R.layout.fifth:
Toast.makeText(getApplicationContext(), "fifth", Toast.LENGTH_SHORT).show();
iv5.setBackgroundResource(R.drawable.ic_launcher);
break;
default:
break;
}
mPosition++;
mButton = (Button)findViewById(R.id.btnid);
mButton.setOnClickListener(mListener);
}
}, 2050);
}
};
mPosition++;
mButton = (Button)findViewById(R.id.btnid);
mButton.setOnClickListener(mListener);
}
}, 750);
}
};
}
任何帮助都非常有用。
答案 0 :(得分:0)
您可以使用android:标签来区分按钮。
<Button
...
android:tag="1"/>
然后在代码中检索标记
mButton = (Button)findViewById(R.id.btnid);
int id = Integer.parseInt(mButton.getTag());
switch(id) {
...
}