2016-02-07 55 views
2

我有兩個類似的按鈕Android的自定義工具欄onOptionsItemSelected不工作

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout 
xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="fill_parent" 
android:layout_height="match_parent" 
android:orientation="horizontal" > 
<Button 
    android:id="@+id/sync_button" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="Sync" 
    android:layout_alignParentEnd="true" 
    android:layout_alignParentRight="true" 
    /> 

</RelativeLayout> 

添加項目到菜單

<menu xmlns:app="http://schemas.android.com/apk/res-auto" 
xmlns:android="http://schemas.android.com/apk/res/android"> 
<item 
    android:id="@+id/toggle_item" 
    android:title="" 
    app:showAsAction="always" 
    app:actionLayout="@layout/switch_button" 
    /> 
<item 
android:id="@+id/sync_item" 
android:title="" 
app:showAsAction="always" 
app:actionLayout="@layout/sync" 
/> 
</menu> 

我膨脹的項目菜單中onCreateOptionsMenu與

getMenuInflater().inflate(R.menu.menu_main, menu); 

一切似乎好,但是當我點擊應用程序時,沒有任何反應,因爲onOptionsItemSelected(MenuItem項)是n曾經被稱爲

@Override 
public boolean onOptionsItemSelected(MenuItem item) { 
    Integer test = item.getItemId(); 
    switch (item.getItemId()) { 
     case R.id.toggle_item: 
      ... 
     case R.id.sync_item: 
      ... 
    return super.onOptionsItemSelected(item); 
} 

添加工具欄與

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
setSupportActionBar(toolbar); 
+1

的([使用actionLayout(SherlockActionBar)時,onOptionsItemSelected不叫]可能的複製http://stackoverflow.com/questions/11627892/onoptionsitemselected-not-called-when-using- actionlayout-sherlockactionbar) –

+0

我試着在它旁邊添加標準項目,這個項目在點擊時觸發事件,我的自定義與定義的actionLayout不同。 – user2925656

回答

0

我終於找到了答案。這兩個答案的結合解決了我的問題:

https://stackoverflow.com/a/17764895/2925656

https://stackoverflow.com/a/23936117/2925656

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    MenuInflater inflater = getMenuInflater(); 
    inflater.inflate(R.menu.main_menu, menu); 
    final Menu m = menu; 
    final MenuItem item = menu.findItem(R.id.sync_button); 
    item.getActionView().setOnClickListener(new OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      do_stuff; 
     } 
    }); 
    return true; 
} 

菜單項:

<item 
    android:id="@+id/myswitch" 
    android:title="" 
    app:showAsAction="always" 
    app:actionLayout="@layout/toggle" /> 

積極佈局必須實現:

android:clickable="false" 

我的切換動作佈局:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="fill_parent" 
android:layout_height="wrap_content" 
android:clickable="false"> 
<ToggleButton 
     android:id="@+id/actionbar_service_toggle" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:textOn="Discovery" 
    android:textOff="Favourite" 
    android:clickable="false"/> 
</RelativeLayout>