没有调用ListFragment onListItemClick,只有CustomAdapter才能完成这项工作

时间:2018-02-18 17:33:53

标签: android listview android-arrayadapter android-listfragment

标题不言自明。我已经经历过很多关于onListItemClick没有被ListFragment调用的问题,我发现没有一个答案对我有用。

我尝试在我的项目xml中使用android:descendantFocusability="blocksDescendants",我尝试手动实现setOnItemClickListener,但到目前为止都没有。

侦听项目单击的唯一技巧是在我的自定义适配器中手动设置侦听器,但我想使用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>

2 个答案:

答案 0 :(得分:0)

如果您要将数据加载到ListView,则不必使用ListFragment(但即使您使用它也会有效)。要处理ListView项目单击,请使用setOnItemClickListener()将OnItemClickListener设置为listview。

答案 1 :(得分:0)

对我来说,触发onListItemClick并且我还没有在任何地方阅读的答案一直是getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE) onActivityCreated ListFragment方法。

@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"