Android在Adapter中对单个item添加组件

2019-03-26  本文已影响0人  Killshadow

效果图:


实现方式

  1. 先在对应item项目组件的xml中把想要添加的组件隐藏:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="horizontal">

    <CheckBox
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/record_detail_interview_content_cb"
        android:layout_gravity="center_vertical"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/record_detail_interview_content_tv"
        android:layout_gravity="right|center_vertical"
        tools:text="健康飲食"/>

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginRight="5dp"
        android:layout_marginLeft="5dp"
        <!-- 想要隐藏的组件, 设为invisible -->
        android:visibility="invisible"
        android:id="@+id/record_detail_interview_content_other_et"
        android:layout_gravity="center|right"
        android:gravity="center_horizontal"/>
</LinearLayout>
  1. adapter中添加一个判断, 到了想要添加组件的那个item就把那个组件设为visible:
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
    if(holder instanceof MultiViewHolder){
        final MultiViewHolder viewHolder = (MultiViewHolder) holder;
        viewHolder.mTvName.setText(datas.get(position));
        viewHolder.mCheckBox.setChecked(isSelected.get(position));
        // 如果为那个组件, 则把EditText设为可视
        if (position == 8) {
            EditText mEditText = holder.itemView.findViewById(R.id.record_detail_interview_content_other_et);
            mEditText.setVisibility(View.VISIBLE);
            mEditText.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                }
            });
        }
        viewHolder.itemView.setSelected(isSelected.get(position));

        viewHolder.itemView.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                isSelected.put(position, isSelected.get(position) ? false : true);
                notifyItemChanged(position);
            }
        });
    }
}
上一篇下一篇

猜你喜欢

热点阅读