Android - How to access actionbar's menu items in fragment class

前端 未结 5 1645
别那么骄傲
别那么骄傲 2020-12-08 19:29

How should I access the actionbar\'s menu items in fragment ? I have tried this but nothing happened

@Override
public boolean onOptionsItemSelected(MenuItem          


        
相关标签:
5条回答
  • 2020-12-08 19:31

    In your fragments onCreate method add setHasOptionsMenu(true);.

    If your fragment is in a ViewPager then the fragment with the ViewPager also needs the above line.

    0 讨论(0)
  • 2020-12-08 19:32

    Menu item main.xml file :

    <menu xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        tools:context="dbl.contact.manager.MainActivity" >
    
        <item
            android:id="@+id/menu_search"
            android:actionLayout="@layout/action_bar"
            android:icon="@drawable/searchagain"
            android:orderInCategory="0"
            android:showAsAction="always"
            android:title="search"/>
    
    </menu>
    

    This is Menu item. custom action bar like edittext in the action bar You have to create a custom layout. Here custom action_bar.xml file :

    <?xml version="1.0" encoding="utf-8"?>
    
    <EditText 
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/inputSearch"
        android:layout_width="280dp"
        android:layout_height="40dp"
        android:cursorVisible="true"  
        android:hint="Search"
        android:imeOptions="actionDone"
        android:inputType="text"
        android:textColor="@android:color/white"
        android:textCursorDrawable="@android:color/white" />
    

    Then in the fragment class you to override. Just Copy and paste this code.

    @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setHasOptionsMenu(true);
        }
    
        @Override
        public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
            // TODO Add your menu entries here
            super.onCreateOptionsMenu(menu, inflater);
             getActivity().getMenuInflater().inflate(R.menu.main, menu);
             View v = (View) menu.findItem(R.id.menu_search).getActionView();
             inputSearch = (EditText)v.findViewById(R.id.inputSearch);
    
                inputSearch.addTextChangedListener(new TextWatcher() {
    
                    @Override
                    public void afterTextChanged(Editable s) {
                        // TODO Auto-generated method stub
                        // clientAdapter.getFilter().filter(s.toString());
                    }
    
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count,
                            int after) {
                        // TODO Auto-generated method stub
                        // ListData.this.clientAdapter.getFilter().filter(s);
                    }
    
                    @Override
                    public void onTextChanged(CharSequence s, int start, int before,
                            int count) {
                        // TODO Auto-generated method stub
    
                        adapter.getFilter().filter(s.toString());
    
                    }
    
                });
    
        }
    
    0 讨论(0)
  • 2020-12-08 19:36

    You cant access directly ActionBar menu items in a Fragment. What you can do is put setHasOptionsMenu(true); in onCreateView function in fragment class and this calls the function onCreateOptionsMenu(Menu menu) in the corresponding activity.

    There, you can access all the menu items you have in the action bar. You can use:

    MenuItem item = menu.getItem(index);
    

    You have one example of using this:

    in fragment onCreateView class:

    setHasOptionsMenu(true);
    

    in corresponding activity class:

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        MenuItem item = menu.getItem(0);
        if(condition)
            item.setVisible(true);
        else 
            item.setVisible(false);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }
        // Handle action bar actions click
        switch (item.getItemId()) {
           case R.id.action_logout:
               makeLogout();
               return  true;
           default :
               return super.onOptionsItemSelected(item);
        }
    
    }
    
    0 讨论(0)
  • 2020-12-08 19:37

    Follow this steps:

    • Add setHasOptionsMenu(true) method in your Fragment.

    • Override onCreateOptionsMenu(Menu menu, MenuInflater inflater) and onOptionsItemSelected(MenuItem item) methods in your Fragment.

    • Inside your onOptionsItemSelected(MenuItem item) Activity's method, make sure you return false when the menu item action would be implemented in onOptionsItemSelected(MenuItem item) Fragment's method.

    Example:

    Activity

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getSupportMenuInflater();
        inflater.inflate(R.menu.main, menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.activity_menu_item:
            // Do Activity menu item stuff here
            return true;
        case R.id.fragment_menu_item:
            // Not implemented here
            return false;
        default:
            break;
        }
    
        return false;
    }
    

    Fragment

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
        ....
    }
    
    @Override
    public void onCreateOptionsMenu(Menu menu,MenuInflater inflater) {
        // Do something that differs the Activity's menu here
        super.onCreateOptionsMenu(menu, inflater);
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.activity_menu_item:
            // Not implemented here
            return false;
        case R.id.fragment_menu_item:
            // Do Fragment menu item stuff here
            return true;
        default:
            break;
        }
    
        return false;
    }
    
    0 讨论(0)
  • 2020-12-08 19:52

    One thing I would add to this (my reputation does not allow me to comment) and reason it was not working for me.

    Make sure your fragment's hosting activity extends AppCompatActivity not FragmentActivity!

    public class MainActivity extends AppCompatActivity {
    
    }
    

    From the Google Reference Documentation for FragmentActivity:

    Note: If you want to implement an activity that includes an action bar, you should instead use the ActionBarActivity class, which is a subclass of this one, so allows you to use Fragment APIs on API level 7 and higher.

    ActionBarActivity now being deprecated, use AppCompatActivity instead. When using AppCompatActivity, also make sure you set "the activity theme to Theme.AppCompat or a similar theme" (Google Doc too).

    android.support.v7.app.AppCompatActivity is a subclass of the android.support.v4.app.FragmentActivity class (see AppCompatActivity ref doc).

    0 讨论(0)
提交回复
热议问题