Today's Question:  What are bad parts of Windows 10?       GIVE A SHOUT

Technical Article => Mobile =>  Android

Add ContextMenu to a customized View in Android

 sonic0002     2012-11-04 07:10:40      5,230    0    0

In Android, we may sometimes need to add ContextMenu to a View, it's not so easy to add ContextMenu to a customized View. Here we explain how to add ContextMenu to a customized View.

First, we may need to create View.OnCreateContextMenuListener so that the customized view can register for it.

Here is the class definition:

public class GraphView extends View {

    private View.OnCreateContextMenuListener vC = new View.OnCreateContextMenuListener() {
        @Override
        public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
            menu.add(Menu.NONE,R.id.graph_view_refresh,Menu.NONE,"Refresh");
            menu.add(Menu.NONE,R.id.save,Menu.NONE,"Save");
        }
    };

    public GraphView(Context context,AttributeSet attrs) {
        super(context,attrs);

        this.setOnCreateContextMenuListener(vC);
    }

}


That's all. Then when you add the View into your Activity. To show the ContextMenu, you only need to call showContextMenu(); then the ContextMenu will show up.

Also, in the Activity class, you may need to listen to the ContextMenu item selection event. In the Activity class, you only need to override the below method :

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();  
        switch (item.getItemId()) {
            case R.id.graph_view_refresh:
                
                return true;
            case R.id.save:
                if(currentView!=null){
                    currentView.save();
                }
                return true;
            default:
                return super.onContextItemSelected(item);
        }
    }

Hope this will help those who are struggling with making ContextMenu work in the customized view.

 Tags : Android, ContextMenu,Customized view   Read(5,230) Comment(0) Version(0)

  SAVE AS PDF   MARK AS READ   MARK AS IMPORTANT

 RELATED


 COMMENT  (TOTAL 0 COMMENT)


No comment for this article.


Nickname  
Email 
Comment

Write in Go

By sonic0002
A song about Go language which learns from the famous song Let it go.   Here is the subscript: Solo The Schedule's tight on the cluster tonight So I parallelized my code   All those threads and continuations My Head's going to explode   And all that boilerplate That FactoryBuilderAda

 CONTRIBUTE


Share your geeky stuff now.
You make the world better, the world makes us better.

 WRITE ARTICLE

 VERSION


No other version available yet.