简体   繁体   English

如何在 ListView 项目中长按时调用上下文菜单?

[英]How do i call a context menu on longclick in a ListView Item?

HomeFragment主页片段

imports;进口;

public class HomeFragment extends Fragment {

// Declare Variables
    ListView list;
    TextView text;
    ListViewAdapter adapter;
    EditText editsearch;
    String[] title;
    String[] date;
    String[] status;
    ArrayList<ListCourse> arraylist = new ArrayList<ListCourse>();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_home, container, false);

        date = new String[] { "11/01/2011", "10/05/2006", "12/07/2002", "05/04/2011", "01/08/2012",
                          "09/12/2017", "22/06/2024", "31/01/2000", "10/10/2156", "10/02/2006" };

        title = new String[] { "Programação", "Matemática", "Logística",
            "Mobile", "Sistemas Operativos", "iOS", "Android", "Windows",
            "Hardware", "Formação" };

        status = new String[] { " ongoing ", " ongoing ",
            " ongoing ", " standby ", " ongoing ", " ongoing ",
            " ongoing ", " ongoing ", " finished ", " ongoing " };

        // Locate the ListView in listview_main.xml

        list = (ListView) rootView.findViewById(R.id.listview);

        for (int i = 0; i < title.length; i++) 
        {
            ListCourse wp = new ListCourse(date[i], title[i],
                status[i]);
            // Binds all strings into an array
            arraylist.add(wp);
        }

        // Pass results to ListViewAdapter Class
        adapter = new ListViewAdapter(getActivity(), arraylist);

        // Binds the Adapter to the ListView
        list.setAdapter(adapter);

       return rootView;
    }
}

I just need 3 items on the context menu: Like, Comment and Favorite.我只需要上下文菜单中的 3 个项目:喜欢、评论和收藏夹。 I tried implementing various tutorials to no avail, my project consist of a MainActivity that has a slidermenu to open some fragments like this one where the list is and where I want to put the context menu.我尝试实施各种教程都无济于事,我的项目由一个 MainActivity 组成,它有一个 slidermenu 来打开一些片段,比如列表所在的片段以及我想放置上下文菜单的片段。

Here´s my adapter:这是我的适配器:

public class ListViewAdapter extends BaseAdapter {

    // Declare Variables
    Context mContext;
    LayoutInflater inflater;
    private List<ListCourse> coursepopulatelist = null;
    private ArrayList<ListCourse> arraylist;

    public ListViewAdapter(Context context, List<ListCourse> coursepopulatelist) {
        mContext = context;
        this.coursepopulatelist = coursepopulatelist;
        inflater = LayoutInflater.from(mContext);
        this.arraylist = new ArrayList<ListCourse>();
        this.arraylist.addAll(coursepopulatelist);
    }

    public class ViewHolder {
        TextView title;
        TextView date;
        TextView status;
    }

    @Override
    public int getCount() {
        return coursepopulatelist.size();
    }

    @Override
    public ListCourse getItem(int position) {
        return coursepopulatelist.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    public View getView(final int position, View view, ViewGroup parent) {
        final ViewHolder holder;
        if (view == null) {
            holder = new ViewHolder();
            view = inflater.inflate(R.layout.listview_item, null);
            // Locate the TextViews in listview_item.xml
            holder.title = (TextView) view.findViewById(R.id.title);
            holder.date = (TextView) view.findViewById(R.id.date);
            holder.status = (TextView) view.findViewById(R.id.status);
            view.setTag(holder);
        } else {
            holder = (ViewHolder) view.getTag();
        }
        // Set the results into TextViews
        holder.title.setText(coursepopulatelist.get(position).getTitle());
        holder.date.setText(coursepopulatelist.get(position).getDate());
        holder.status.setText(coursepopulatelist.get(position).getStatus());

        // Listen for ListView Item Click
        view.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // Send single item click data to SingleItemView Class
                Intent intent = new Intent(mContext, SingleItemView.class);
                // Pass all data rank
                intent.putExtra("title",(coursepopulatelist.get(position).getTitle()));
                // Pass all data country
                intent.putExtra("date",(coursepopulatelist.get(position).getDate()));
                // Pass all data population
                intent.putExtra("status",(coursepopulatelist.get(position).getStatus()));
                // Pass all data flag
                // Start SingleItemView Class
                mContext.startActivity(intent);
            }
        });

        return view;
    }

    // Filter Class
    public void filter(String charText) {
        charText = charText.toLowerCase(Locale.getDefault());
        coursepopulatelist.clear();
        if (charText.length() == 0) {
            coursepopulatelist.addAll(arraylist);
        } 
        else 
        {
            for (ListCourse wp : arraylist) 
            {
                if (wp.getDate().toLowerCase(Locale.getDefault()).contains(charText)) 
                {
                    coursepopulatelist.add(wp);
                }
            }
        }
        notifyDataSetChanged();
    }

}

Are the changes supposed to go in the adapter or the fragment?适配器或片段中的更改应该为 go 吗? I tried several times with OnCreateContextMenu and ContextMenuSelectedItem cant get it to work on the fragment, also tried OnLongItemClick.我尝试了几次 OnCreateContextMenu 和 ContextMenuSelectedItem 无法让它在片段上工作,也尝试了 OnLongItemClick。 Any help would be appreciated.任何帮助,将不胜感激。

You have to set setOnItemLongClickListener() in the ListView: 您必须在ListView中设置setOnItemLongClickListener():

lv.setOnItemLongClickListener(new OnItemLongClickListener() {

            public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
                    int pos, long id) {

                // Do stuff here

                return true;
            }
        }); 

Also, you need to set it on the list not inside the adapter (if that was your doubt) 另外,您需要将其设置在列表中,而不是在适配器内部(如果您对此表示怀疑)

EDIT: You need to do this inside the onCreate() method. 编辑:您需要在onCreate()方法中执行此操作。

first set your listvieW as follow myListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); 首先按照myListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);设置listvieW myListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

        myListView.setAdapter(adapter);

then register for MultiChoiceModeListener and override his methods in your liking :) 然后注册MultiChoiceModeListener并根据自己的喜好覆盖他的方法:)

        myListView.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
            @Override
            public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {

            }

            @Override
            public boolean onCreateActionMode(ActionMode mode, Menu menu) {
               // here you will inflate your CAB
                return true;
            }

            @Override
            public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
                return false;
            }

            @Override
            public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
                return false;
            }

            @Override
            public void onDestroyActionMode(ActionMode mode) {

            }
        });

    }

Here is the link 链接在这里

i hope it help 希望对您有帮助

Edit : add a link that could help you 编辑:添加可以帮助您的链接

I managed to get one context menu working, right here: 我设法在这里找到一个上下文菜单:

       @Override
       public void onCreateContextMenu(ContextMenu menu, View v,
            ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);

        AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
        adapter = new ListViewAdapter(getActivity(), arraylist);
        Object item = adapter.getItem(info.position);

        menu.setHeaderTitle("Opções");
        menu.add(0, v.getId(), 0, "Like");
        menu.add(1, v.getId(), 0, "Comment");
        menu.add(2, v.getId(), 0, "Favorite");

        }


        @Override   
        public boolean onContextItemSelected(MenuItem item) {
        if (item.getTitle() == "Like") {
            addLike(item.getItemId());
        } else if (item.getTitle() == "Comment") {

        } else if (item.getTitle() == "Favorite") {
            // code
        } else {
            return false;
        }
        return true;

        }

        public void addLike(int id){

        }

Right after the return rootView in the HomeFragment. 在HomeFragment中返回rootView之后。 Also had to add android:longClickable="true" on the listview.xml or it would never work (I put it into the listviewitem.xml too just in case). 还必须在listview.xml上添加android:longClickable =“ true”,否则它将永远无法工作(为防万一,我将其放入listviewitem.xml中)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM