ListView中CheckBox在代码中setCheck无效原因

xiaoxiao2021-02-28  75

之前做一个listView多选效果,于是用到checkbox,众所周知需要将checkbox的focusable置为”false”才可以点击

代码如下所示:

XML布局代码 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="60dp"> <TextView android:layout_width="wrap_content" android:gravity="center" android:focusable="false" android:layout_height="match_parent" android:id="@+id/tv_payType"/> <CheckBox android:layout_width="wrap_content" android:layout_height="match_parent" android:gravity="center" android:focusable="false" android:clickable="false" android:layout_alignParentRight="true" android:layout_marginRight="@dimen/margin_normal" android:id="@+id/cb_payType"/> </RelativeLayout> Adapter代码 public class PayTypeSelectAdapter extends BaseAdapter { private List<PayType> mPayTypes; private LayoutInflater mLayoutInflater; public PayTypeSelectAdapter(Context context, List<PayType> payTypes){ mPayTypes = payTypes; mLayoutInflater = LayoutInflater.from(context); } @Override public int getCount() { return mPayTypes.size(); } @Override public Object getItem(int position) { return mPayTypes.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; PayType payType = mPayTypes.get(position); if (convertView == null){ convertView = mLayoutInflater.inflate(R.layout.item_pay_type,null,false); holder = new ViewHolder(); holder.cb_payType = (CheckBox) convertView.findViewById(R.id.cb_payType); holder.tv_payType = (TextView) convertView.findViewById(R.id.tv_payType); convertView.setTag(holder); }else{ holder = (ViewHolder) convertView.getTag(); } holder.tv_payType.setText(payType.getPayType()); holder.cb_payType.setChecked(payType.isSelected()); return convertView; } class ViewHolder{ TextView tv_payType; CheckBox cb_payType; } }

然后在使用的地方对ListView进行点击监听,将PayType对象的属性置为true或false,然后通知adapter更新。

但是问题来了,点击后竟然选中一下又消失,反反复复检查代码都没问题,那么 问题出在哪里呢?

查阅了很多资料都没有答案,后来灵机一动,会不会是checkBox的android:layout_height=”match_parent” 出了问题,于是将其改为“wrap_content”,问题解决!

转载请注明原文地址: https://www.6miu.com/read-54106.html

最新回复(0)