【发布时间】:2017-04-10 16:40:06
【问题描述】:
如果我按下其他位置(不是单选按钮)但在 1 线性布局内的图像、文本视图等上按下,如何使单选按钮被选中。
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:id="@+id/layout_1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:id="@+id/card_balance"
android:layout_width="150dp"
android:layout_height="150dp"
android:layout_gravity="center_vertical"
android:paddingLeft="20dp" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:paddingLeft="10dp"
android:textColor="@color/dc_white" />
<RadioGroup
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:gravity="right"
android:paddingRight="20dp">
<RadioButton
android:id="@+id/radio_button_payment"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RadioGroup>
</LinearLayout>
</RelativeLayout>
这里是适配器:PaymentAdapter.java
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View allView = inflater.inflate(R.layout.item_choose_payment, parent, false);
TextView txt1 = (TextView) allView.findViewById(R.id.textView1);
ImageView imageView = (ImageView) allView.findViewById(R.id.card_balance);
final RadioButton r = (RadioButton) allView.findViewById(R.id.radio_button_payment);
LinearLayout layout_card = (LinearLayout) allView.findViewById(R.id.layout_1);
r.setChecked(position == selectedPosition);
r.setTag(position);
r.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
selectedPosition = (Integer) view.getTag();
notifyDataSetChanged();
}
});
}
现在的条件是我只能在单选按钮上按下。
我已经尝试将 onClickListener 添加到线性布局,是的,我可以在线性布局上按下,但是单选按钮不仅选择 1,而是全部选择。
linearLayout onClick 的代码
layout_card.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
r.setChecked(position == selectedPosition);
r.setTag(position);
if (r.isChecked()) {
r.setChecked(true);
r.setSelected(true);
} else if (!r.isChecked()) {
r.setChecked(false);
r.setSelected(false);
}
}
});
对不起,我的解释不好,任何帮助都非常感谢我。 谢谢
【问题讨论】:
-
使用 setChecked(true) 方法
-
我应该把那个方法放在哪里? @hosseinAmini
-
你有多少单选按钮,因为我在你的 xml 中只看到一个,但在你的解释中你说所有单选按钮都被选中而不是一个..
-
这是一个动态单选按钮,我有 4 个虚拟数据,所以它出现 4 个单选按钮或 4 个线性布局取决于数据。 @Moulesh
-
标签: android android-layout radio-button android-linearlayout