簡體   English   中英

動作欄-拖動菜單項

[英]Action Bar - Drag Menu Item

我如何將OnTouchListener設置為操作欄菜單項,以添加從操作欄拖動某些項目的功能?

例如,如果我這樣做:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">

        <item android:id="@+id/my_menu_item_button"
            android:icon="@android:drawable/ic_menu_mylocation"
            android:title="TEST"
            app:showAsAction="always"  />

</menu>

並嘗試這樣做:

final MenuItem myMenuItem = (MenuItem) findViewById(R.id.action_search);

myMenuItem.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent me) {             
        return true;
    }
});

我不能,因為setOnTouchListener需要視圖。

有什么解決辦法嗎?

這是骨架: https : //gist.github.com/anonymous/b654b67d4dbd45ce8539

View you can find easily by using menuItem.getActionView(), but I guess you get the action view as null if you have not set any custom view using MenuItem.setActionView().

Solution : 
Lets create a layout file called sample_action_view.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_gravity="center_vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <ImageView
        android:id="@+id/mobile_link_action_bar_button" 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" 
        android:paddingTop="10dp"
        android:paddingBottom="10dp"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:src="sampleImage.png"
        android:contentDescription="Sample Image"/>    
</LinearLayout>


    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        getMenuInflater().inflate(R.menu.menu_main, menu);

        LayoutInflater inflater = (LayoutInflater)this.getApplicationContext().getSystemService
                (Context.LAYOUT_INFLATER_SERVICE);
        View sampleActionView = inflater.inflate(R.layout.sample_action_view, null);
        MenuItem searchMenuItem = menu.findItem(R.id.menu_myDemoToolbarButton);
        serachMenuItem.setActionView(sampleActionView);

        sampleActionView.setOnTouchListener(new OnTouchListener() 
        {
            @Override
            public boolean onTouch(View v, MotionEvent event)
            {
                // TODO Auto-generated method stub
                return false;
            }
        });

        return super.onCreateOptionsMenu(menu);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM