Android - findViewById 方法在片段中查找项目,用于从自定义布局中查找项目



首先,我已经搜索了许多其他帖子,但仍然没有找到修复方法。

MainActivity是一个选项卡式活动(2 个选项卡(,第一个包含ListView。该列表中的单个项目由包含 id 为 deleteItemImageImageViewcustom_row布局文件创建。

如何在Tab1_class中使用findViewById从自定义布局文件中获取对该图像的引用,以便能够setOnClickListener(...)

我已经尝试使用(onCreateView(...)方法(view.findViewById(...)getActivity().findViewById(...)getView().findViewById(...),但没有任何效果。

希望有人能帮忙!!提前谢谢你!!

编辑:

custom_row.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="10dp">
    (...)
    <ImageView
        android:id="@+id/deleteItemImage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:src="@drawable/icon"/>
</RelativeLayout>

Tab1_List.java

(...)
@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.tab1_list, container, false);
        (...)
        //TODO
        ImageView deleteItemImage = (ImageView) rootView.findViewById(R.id.deleteItemImage);
        deleteItemImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // ...
            }
        });
        return rootView;
    }

您需要为适配器项声明侦听器接口。并在Tab1_class中实现 TouchListener。

我希望以下代码会有所帮助...

修改适配器类和视图持有人,例如

public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnTouchListener{
        private ImageView iv_cardImage;
        public MyViewHolder(View itemView) {
            super(itemView);
            iv_cardImage = (ImageView) itemView.findViewById(R.id.iv_cardImage);
            iv_cardImage.setOnTouchListener(this);
        }
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            view.getParent().requestDisallowInterceptTouchEvent(true);
            switch(motionEvent.getAction()){
                case MotionEvent.ACTION_UP:
                    //Toast.makeText(context, "from adapter", Toast.LENGTH_LONG).show();
                    touchListener.itemTouched(view, getAdapterPosition());
                    return true;
            }
            return false;
        }
    }
    public void setTouchListener(TouchListener touchListener){
        this.touchListener = touchListener;
    }

创建单击项目图像视图时要调用的接口

public interface TouchListener{
        void itemTouched(View v, int position);
    }

最新更新