我有多个setOnClickListener,我想做的就是使其更简单。
这是我的java
@Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
// get the button view
ImageView foodImg = (ImageView) getView().findViewById(R.id.iconFoods);
ImageView barsImg = (ImageView) getView().findViewById(R.id.iconBars);
ImageView roomsImg = (ImageView) getView().findViewById(R.id.iconRooms);
ImageView wellnessImg = (ImageView) getView().findViewById(R.id.iconWellness);
ImageView beachesImg = (ImageView) getView().findViewById(R.id.iconBeaches);
ImageView kidsImg = (ImageView) getView().findViewById(R.id.iconKids);
ImageView attractionsImg = (ImageView) getView().findViewById(R.id.iconAttractions);
ImageView shopsImg = (ImageView) getView().findViewById(R.id.iconShops);
ImageView museumsUmg = (ImageView) getView().findViewById(R.id.iconMuseum);
// set a onclick listener for when the food button gets clicked
foodImg.setOnClickListener(new OnClickListener() {
// Start new list activity
public void onClick(View v) {
Intent mainIntent = new Intent(getActivity(),
Food.class);
startActivity(mainIntent);
}
});
// set a onclick listener for when the bars button gets clicked
barsImg.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent mainIntent = new Intent(getActivity(),
Bars.class);
startActivity(mainIntent);
}
});
如您所见,我为每个ImageView创建一个setOnClickListener。
我的问题是,如何对多个setOnClickListener使用if语句?
因此,当我单击ImageView Foods Icon时,我将打开foods活动。
之前感谢:D
最佳答案
创建一个通用的onClickListener
private OnClickListener onClickListener = new OnClickListener() {
@Override
public void onClick(final View v) {
switch(v.getId()){
case R.id.button1:
((TextView) getView().findViewById(R.id.textView1)).setText("Button 1 pushed");
break;
case R.id.button2:
((TextView) getView().findViewById(R.id.textView1)).setText("Button 2 pushed");
break;
case R.id.button3:
((TextView) getView().findViewById(R.id.textView1)).setText("Button 3 pushed");
break;
}
}
};
然后将每个视图设置为使用该点击侦听器,即:
Button btn1 = (Button) getView().findViewById(R.id.button1);
Button btn2 = (Button) getView().findViewById(R.id.button2);
Button btn3 = (Button) getView().findViewById(R.id.button3);
btn1.setOnClickListener(onClickListener);
btn2.setOnClickListener(onClickListener);
btn3.setOnClickListener(onClickListener);
希望能帮助到你。