OnItemClickListener和OnClickListener使用BaseAdapter不适用于ListView

时间:2017-05-17 06:27:34

标签: android listview baseadapter

这是我的代码无效

我使用`AsyncTask`从服务器获取数据,并使用`baseadapter`将数据设置为`listview`,但使用在适配器类中工作的`convertview.setonclicklistner`,下面的代码包含在`Fragmentclass中(导入android.support。 v4.app.Fragment;)`所以我认为这不成问题

 @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    view= inflater.inflate(R.layout.fragment_restaurants, container, false);
    restaurant_list = (ListView)view.findViewById(R.id.restatrant_lv);

    no_restaturants=(TextView)view.findViewById(R.id.no_restaturants);

    // listening to single list item on click
    restaurant_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view,
                                int position, long id) {

            Log.e("temp","temppppp");

        }
    });

    //set layout slide listener
    rowItems = new ArrayList<>();

    history_list = new ArrayList<HashMap<String, String>>();
    list_adapter = new ViewAdapter(getActivity(),rowItems);
    restaurant_list.setAdapter(list_adapter);
}

这是什么解决方案?

2 个答案:

答案 0 :(得分:0)

android:descendantFocusability="blocksDescendants"

如果任何ListView包含可聚焦或可点击的视图,那么OnItemClickListener将无法工作。在这种情况下,我们需要使用它。

设置适配器后尝试设置setOnClickListener:

像这样:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    view= inflater.inflate(R.layout.fragment_restaurants, container, false);
    restaurant_list = (ListView)view.findViewById(R.id.restatrant_lv);

    no_restaturants=(TextView)view.findViewById(R.id.no_restaturants);


    //set layout slide listener
    rowItems = new ArrayList<>();

    history_list = new ArrayList<HashMap<String, String>>();
    list_adapter = new ViewAdapter(getActivity(),rowItems);
    restaurant_list.setAdapter(list_adapter);

// listening to single list item on click
        restaurant_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view,
                                int position, long id) {

            Log.e("temp","temppppp");

        }
    });
}

答案 1 :(得分:0)

将id添加到custom_list_item.xml的父布局

holder.parentLayout.setOnClickListener(new OnClickItem(position));

private class OnClickItem implements View.OnClickListener{
    private int mPostion;

    public OnClickItem(int position){
        mPostion = position;
    }
    @Override
    public void onClick(View v) {
        YourActivity yourActivity = (YourActivity) mContext;
        yourActivity.onItemClicked(mPostion);
    }
}