Android組件ContextMenu實現長按事件

本文實例為大傢分享瞭ContextMenu長按事件的實現具體代碼,供大傢參考,具體內容如下

/**
 *ContextMenu菜單就是長按某一個組件,就會在屏幕的中間彈出ContextMenu,這裡設置為長按文本框彈出   *ContextMenu菜單
 */

public class MyContextMenu extends AppCompatActivity {
    /** 
     *Called when the activity is first created. 
     **/
    final static int CONTEXT_MENU_1 = Menu.FIRST;//可以理解為ID設置的最小數值
    final static int CONTEXT_MENU_2 = Menu.FIRST + 1;
    final static int CONTEXT_MENU_3 = Menu.FIRST + 2;
    TextView textView = null;//設置成員變量
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_context_menu);
        textView = (TextView)findViewById(R.id.label);//獲取text
        registerForContextMenu(textView);//註冊長摁菜單事件
    }

    /**
     *創建菜單
     **/
    @Override
    public void onCreateContextMenu(ContextMenu menu,
                                    View v, ContextMenu.ContextMenuInfo menuInfo){
        menu.setHeaderTitle("快捷菜單標題");//設置標題
        //設置對應id及title
        menu.add(0, CONTEXT_MENU_1, 0,"菜單子項1");
        menu.add(0, CONTEXT_MENU_2, 1,"菜單子項2");
        menu.add(0, CONTEXT_MENU_3, 2,"菜單子項3");
    }

    /**
     *設置對應事件
     **/
    @Override
    public boolean onContextItemSelected(MenuItem item){
        switch(item.getItemId()){
            case CONTEXT_MENU_1:
                Toast.makeText(MyContextMenu.this,"選中菜單子項1",Toast.LENGTH_SHORT).show();
                return true;
            case CONTEXT_MENU_2:
                Toast.makeText(MyContextMenu.this,"選中菜單子項2",Toast.LENGTH_SHORT).show();
                return true;
            case CONTEXT_MENU_3:
                Toast.makeText(MyContextMenu.this,"選中菜單子項3",Toast.LENGTH_SHORT).show();
                return true;
        }
        return false;
    }

    public void skip(View v){
        Intent intent = new Intent();
        intent.setClass(MyContextMenu.this,TabDemo.class);//從前者跳往後者
        startActivity(intent);//啟動
    }
}

xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".MyContextMenu"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <TextView android:id="@+id/label"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello"
        />

</LinearLayout>

效果圖:

以上就是本文的全部內容,希望對大傢的學習有所幫助,也希望大傢多多支持WalkonNet。

推薦閱讀:

    None Found