ListFragment onListItemClick 未调用,只有 CustomAdapter 完成这项工作

ListFragment onListItemClick not called, only CustomAdapter does the job

标题self-explanatory。我已经回答了很多关于 onListItemClickListFragment 中没有被调用的问题,我发现 none 的答案对我有用。

我曾尝试在我的项目 xml 中使用 android:descendantFocusability="blocksDescendants",我曾尝试手动实施 setOnItemClickListener,但 none 目前有效。

监听项目点击的唯一技巧是在我的自定义适配器中手动设置监听器,但我想使用 onListItemClick,因为这是预期的。请找到下面的代码,如果您能找出 onListItemClick 未被调用的原因,我将不胜感激。

ListFragment

public class BrowseFragment extends ListFragment {

    final String TAG = "BrowseFragment";
    private ArrayList<Event> mEvents = new ArrayList<>();
    private ListView mList;
    private SwipeRefreshLayout mSwipeRefreshLayout;
    private EventListArrayAdapter mAdapter;

    public BrowseFragment() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRetainInstance(true);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_browse, container, false);
        mList = (ListView) v.findViewById(android.R.id.list);
        mSwipeRefreshLayout = (SwipeRefreshLayout) v.findViewById(R.id.pullToRefresh);
        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                // TODO Auto-generated method stub
                mSwipeRefreshLayout.setRefreshing(true);
                refreshContent();
            }
        });

        setHasOptionsMenu(true);
        return v;
    }

    private void refreshContent() {
        FirebaseFirestore.getInstance().collection("events").get()
                .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                    @Override
                    public void onComplete(@NonNull Task<QuerySnapshot> task) {
                        if (task.isSuccessful()) {
                            mEvents.clear();
                            for (DocumentSnapshot document : task.getResult()) {
                                Log.d(TAG, document.getId() + " => " + document.getData());
                                mEvents.add(document.toObject(Event.class));
                            }
                            mAdapter.notifyDataSetChanged();
                            mSwipeRefreshLayout.setRefreshing(false);
                        } else {
                            Log.d(TAG, "Error getting documents: ", task.getException());
                        }
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        Log.d(TAG, "Failure", e);
//                        loadingPanel.setVisibility(View.INVISIBLE);
                        mSwipeRefreshLayout.setRefreshing(false);
                    }
                });
    }

    @Override
    public void onViewCreated(final View view, Bundle savedInstanceState) {
        if (mEvents.isEmpty()) {
            FirebaseFirestore.getInstance().collection("events").get()
                    .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                        @Override
                        public void onComplete(@NonNull Task<QuerySnapshot> task) {
                            if (task.isSuccessful()) {
                                for (DocumentSnapshot document : task.getResult()) {
                                    Log.d(TAG, document.getId() + " => " + document.getData());
                                    mEvents.add(document.toObject(Event.class));
                                }
                                mAdapter.notifyDataSetChanged();
                            } else {
                                Log.d(TAG, "Error getting documents: ", task.getException());
                            }
                        }
                    })
                    .addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception e) {
                            Log.d(TAG, "Failure", e);
                        }
                    });
        }
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mAdapter = new EventListArrayAdapter(this.getActivity(), mEvents);
        new EventListArrayAdapter(this.getActivity(), mEvents);
        mList.setAdapter(mAdapter);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.menu_serach, menu);
        super.onCreateOptionsMenu(menu, inflater);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_search:
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    // CODE BELOW IS NOT TRIGGERED

    @Override
    public void onListItemClick(ListView l, View v, int pos, long id) {
        super.onListItemClick(l, v, pos, id);
        Toast.makeText(getActivity(), "Item " + pos + " was clicked", Toast.LENGTH_SHORT).show();
    }
}

CustomAdaper

public class EventListArrayAdapter extends ArrayAdapter<Event> {

    private final ArrayList<Event> mList;
    private final Activity context;

    static class ViewHolder {
        protected TextView title;
        protected ImageView cat_pic;
    }

    public EventListArrayAdapter(Activity context, ArrayList<Event> list) {
        super(context, R.layout.list_event_row, list);
        this.context = context;
        this.mList = list;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        View row = convertView;
        ViewHolder holder = null;

        if (row == null) {
            LayoutInflater inflater = context.getLayoutInflater();
            row = inflater.inflate(R.layout.list_event_row, parent, false);
            holder = new ViewHolder();
            holder.title = (TextView) row.findViewById(R.id.title);
            holder.cat_pic = (ImageView) row.findViewById(R.id.category_img);
            row.setTag(holder);
        } else {
            holder = (ViewHolder) row.getTag();
        }

        holder.title.setText(mList.get(position).getTitle());
        Map<String, Boolean> cats = mList.get(position).getCategory();
        String cat_keyval = cats.keySet().iterator().next();
        holder.cat_pic.setImageResource(MyUtilFunctions.categoryIcons(cat_keyval));

// ******* THE CODE BELOW TRIGGERS THE CLICK BUT I WANT TO SET THIS IN MY LISTFRAGMENT **************

//        row.setOnClickListener(new AdapterView.OnClickListener(){
//            @Override
//            public void onClick(View v) {
//                Log.v("text", "Title clicked " + mList.get(position).getEvent_id());
//                Intent myIntent = new Intent(context, EventInfoActivity.class);
//                myIntent.putExtra("EVENT_ID", mList.get(position).getEvent_id());
//                context.startActivity(myIntent);
//
//            }
//        });

        return row;
    }

}

片段XML

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.hobbypop.Fragments.BrowseFragment">
    <android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/pullToRefresh"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:layout_marginStart="5dp"
        android:layout_marginEnd="5dp"
        android:layout_marginBottom="10dp">
        <ListView
            android:id="@android:id/list"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:divider="@android:color/transparent"
            android:focusable="true"
            android:focusableInTouchMode="true"
            android:dividerHeight="10.0dp">
        </ListView>
    </android.support.v4.widget.SwipeRefreshLayout>
</RelativeLayout>

项目XML

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/linear_list"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:background="@drawable/rounded_corners_3"
    android:descendantFocusability="blocksDescendants"
    android:elevation="5dp">
    <RelativeLayout
        android:id="@+id/mainLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <ImageView
            android:id="@+id/category_img"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_category"
            android:layout_marginTop="3dp"/>
        <TextView
            android:id="@+id/title"
            android:textSize="18sp"
            android:textStyle="bold"
            android:text="Title"
            android:layout_alignStart="@id/category_img"
            android:layout_alignBottom="@id/category_img"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginStart="32dp"
            android:layout_marginBottom="4dp"/>
    </RelativeLayout>
</LinearLayout>

如果您使用 setOnItemClickListener() 将数据加载到列表视图 ListView, you don't have to use a ListFragment (However it will work even if you use). To handle ListView item clicks, set an OnItemClickListener

对我有效触发 onListItemClick 并且我还没有在任何地方阅读的答案是在 [=14= 的 onActivityCreated 方法上设置 getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE) ].

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    mAdapter = new EventListArrayAdapter(this.getActivity(), mEvents);
    new EventListArrayAdapter(this.getActivity(), mEvents);
    mList.setAdapter(mAdapter);
    getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
}

不需要使用xml项中的android:descendantFocusability="blocksDescendants"