【发布时间】:2021-02-03 17:57:45
【问题描述】:
我正在尝试使图像按钮的行为类似于单选按钮。让我解释。我有一个包含图像按钮和 TextView 的基本布局,我加载了不同的图像和文本。
XML 布局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageButton
android:id="@+id/button_category"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="#FFFFFF"/>
<TextView
android:id="@+id/text_category"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"/>
</LinearLayout>
Java 方法:
LinearLayout categoryLayout = view.findViewById(R.id.categories_layout);
for (int i = 0; i<categories.size(); i++) {
final String name = categories.get(i).name;
final int resource = categories.get(i).resource;
View v = getLayoutInflater().inflate(R.layout.choose_category, null);
final TextView text = v.findViewById(R.id.text_category);
text.setText(name);
ImageButton button = v.findViewById(R.id.button_category);
button.setImageResource(resource);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
selectedCategory = resource;
text.setTypeface(text.getTypeface(), Typeface.BOLD);
}
});
categoryLayout.addView(v);
}
每次单击图像时,都会将文本设置为粗体以指示单击了哪个按钮。我的问题是我只希望一次可以点击一个按钮。我想到,每次单击按钮时,都会重置所有 TextView 的外观,只留下最后一次单击的文本为粗体。但是,我不知道如何浏览已生成的所有布局。
我希望我说清楚了,如果你能帮助我,谢谢!
【问题讨论】:
-
尝试使用
tag属性看到这个答案stackoverflow.com/questions/35343138/…你可能需要使用一些逻辑 -
我会为所有单选按钮使用一个自定义
actionListener,它会侦听特定的操作命令,例如活动单选按钮使用的“RADIO_BUTTON_ACTIVE”,而所有非活动单选按钮都有一个操作类似“RADIO_BUTTON_INACTIVE”的命令。