gpt4 book ai didi

java - Android If 语句用于多个 setOnClickListener

转载 作者:行者123 更新时间:2023-12-02 05:44:01 25 4
gpt4 key购买 nike

我有多个 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 图标时,我打开了 Food Activity 。谢谢之前: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;
}
}
};

然后将每个 View 设置为使用该点击监听器,即:

        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);

希望有帮助。

关于java - Android If 语句用于多个 setOnClickListener,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24259964/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com