OnCreateOptionsMenu () ไม่ถูกเรียกใน Fragment


107

ฉันมีแอพที่มีกิจกรรมหนึ่งโดยมี 2 ส่วนวางในแนวนอน

ในกิจกรรมของฉันฉันขยายเมนูโดยonCreateOptionsMenu()ใช้ซึ่งฉันสามารถแสดงเมนูตัวเลือกแถบการทำงานได้ แต่เมื่อฉันพยายามอัปเดตรายการเมนูแถบการดำเนินการจากส่วนหนึ่งของฉันonCreateoptionsmenu()จะไม่มีการเรียกใช้ ดังนั้นฉันจึงไม่สามารถอัปเดตเมนูตัวเลือกแถบการทำงานได้

รหัสในกิจกรรมของฉันมีดังต่อไปนี้:

myActivity.java

package com.andr.androidtablelist;

import java.io.IOException;

import android.app.ActionBar;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;

import com.andr.fragments.ListLeftFragment;
import com.andr.utils.DBHelper;

      public class TabletActivity extends Activity {
    ActionBar actionBar = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        DBHelper dbhelper;
        dbhelper = new DBHelper(this);
        try {
            dbhelper.createDatabase();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        setContentView(R.layout.activity_tablet);
        actionBar = getActionBar();
        actionBar.setDisplayHomeAsUpEnabled(false);
        getFragmentManager().beginTransaction()
                .replace(R.id.master, ListLeftFragment.newInstance()).commit();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.tablet, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case android.R.id.home:
            Toast.makeText(
                    getApplicationContext(),
                    "Back Stack Count::"
                            + getFragmentManager().getBackStackEntryCount(),
                    Toast.LENGTH_LONG).show();
            if (getFragmentManager().getBackStackEntryCount() == 1) {
                actionBar.setDisplayHomeAsUpEnabled(false);
            }
            if (getFragmentManager().getBackStackEntryCount() > 1) {
                getFragmentManager().popBackStack();

            }
            return true;

        }
        return super.onOptionsItemSelected(item);
    }

}
      // http://www.vogella.com/articles/AndroidListView/article.html

myFragment.java

      package com.andr.fragments;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.TextView;

import com.andr.androidtablelist.R;
import com.andr.helper.LazyHelper;

   public class ListLeftFragment extends Fragment{
    private static ListLeftFragment listFragment = null;

    public static ListLeftFragment newInstance(){
        listFragment = new ListLeftFragment();      
        return listFragment;
    }

     @Override
    public void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);


    }

     @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
         View v =  inflater.inflate(R.layout.fragment_listlayout, container,false);
         getActivity().invalidateOptionsMenu();
         ListView lv = (ListView)v.findViewById(R.id.lview);
         String[] values = new String[] { "Android", "iPhone", "WindowsMobile",
                    "Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X",
                    "Linux", "OS/2", "Ubuntu", "Windows7", "Max OS X", "Linux",
                    "OS/2", "Ubuntu", "Windows7", "Max OS X", "Linux", "OS/2",
                    "Android", "iPhone", "WindowsMobile" };
         getActivity().getActionBar().setTitle("LeftList");

          ArrayList<String> list = new ArrayList<String>();
         LazyHelper lHelper = new LazyHelper(getActivity());
         list = lHelper.getLazyDetials();

           /* for (int i = 0; i < values.length; ++i) {
              list.add(values[i]);
            }
            final StableArrayAdapter adapter = new StableArrayAdapter(getActivity(),
                android.R.layout.simple_list_item_1, list);*/
            LeftListAdapter lAdapter = new LeftListAdapter(getActivity(),list);
            lv.setAdapter(lAdapter);
            lv.setOnItemClickListener(new OnItemClickListener()
            {

                @Override
                public void onItemClick(AdapterView<?> arg0, View arg1,
                        int pos, long arg3) {
                    final String clickedData = (String)arg0.getItemAtPosition(pos);
                    Bundle bundle = new Bundle();
                    bundle.putString("clickedItemName", clickedData);
                    Fragment detailFragment = DetailFormRightFragment.newInstance();
                    detailFragment.setArguments(bundle);
                    getActivity().getFragmentManager().beginTransaction().replace(R.id.details, detailFragment).addToBackStack(null).commit();
                }

            }
                    );
         return v;
    }


     @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        getActivity().getMenuInflater().inflate(R.menu.search, menu);
        SearchView searchView=(SearchView)menu.findItem(R.id.search);
        searchView.setIconifiedByDefault(true);
    } 

     @Override
    public boolean onOptionsItemSelected(MenuItem item) {

         super.onOptionsItemSelected(item);
         return false;
    }


     @Override
    public void onPrepareOptionsMenu(Menu menu) {
         super.onPrepareOptionsMenu(menu);
        /*MenuItem item;
        menu.clear();
        getActivity().getMenuInflater().inflate(R.menu.search, menu);
        SearchView searchView=(SearchView)menu.findItem(R.id.search);
        searchView.setIconifiedByDefault(true);*/
    }

     private class StableArrayAdapter extends ArrayAdapter<String> {

            HashMap<String, Integer> mIdMap = new HashMap<String, Integer>();

            public StableArrayAdapter(Context context, int textViewResourceId,
                List<String> objects) {
              super(context, textViewResourceId, objects);
              for (int i = 0; i < objects.size(); ++i) {
                mIdMap.put(objects.get(i), i);
              }
            }

            @Override
            public long getItemId(int position) {
              String item = getItem(position);
              return mIdMap.get(item);
            }

            @Override
            public boolean hasStableIds() {
              return true;
            }

          }

     private class LeftListAdapter extends BaseAdapter implements OnClickListener {
         private Context mcontext;
         ArrayList<String> listData;
         private  LayoutInflater inflater=null;
         public LeftListAdapter(Context context, ArrayList<String> listItems) {
              mcontext=context;
              listData=listItems;
              inflater = (LayoutInflater)mcontext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
         }

        @Override
        public int getCount() {
            return listData.size();
        }

        @Override
        public Object getItem(int arg0) {
            return null;
        }

        @Override
        public long getItemId(int arg0) {
            // TODO Auto-generated method stub
            return 0;
        }

        @Override
        public View getView(int position, View view, ViewGroup arg2) {
            // create a ViewHolder reference
            View vi=view;
            if(vi==null){
                vi = inflater.inflate(R.layout.item, null);
            }
            TextView text=(TextView)vi.findViewById(R.id.text);
            text.setText(listData.get(position));
            vi.setOnClickListener(this);
            return vi;
        }

        @Override
        public void onClick(View vi) {
            TextView text=(TextView)vi.findViewById(R.id.text);
            Bundle bundle = new Bundle();
            bundle.putString("clickedItemName", text.getText().toString());
            Fragment detailFragment = DetailFormRightFragment.newInstance();
            detailFragment.setArguments(bundle);
            getActivity().getFragmentManager().beginTransaction().replace(R.id.details, detailFragment).addToBackStack(null).commit();          
        }

     }
   }

คำตอบ:


296

ในonCreateView()วิธีการของแฟรกเมนต์ของคุณคุณต้องโทรsetHasOptionsMenu(true)เพื่อบอกกิจกรรมของโฮสต์ว่าแฟรกเมนต์ของคุณมีตัวเลือกเมนูที่ต้องการเพิ่ม


ฉันทำการเปลี่ยนแปลง แต่แอพขัดข้องเมื่อ 11-27 01: 55: 34.468: E / AndroidRuntime (12294): เกิดจาก: java.lang.ClassCastException: com.android.internal.view.menu.MenuItemImpl ไม่สามารถส่งไปยัง Android ได้ .widget.SearchView
Android_programmer_office

ใช่ฉันพบปัญหา ลืมเพิ่ม getActionView () สำหรับ searchView
Android_programmer_office

2
นอกจากนี้คุณต้องใช้ประเภทโมฆะสำหรับ onCreateOptionsMenu (เมนู Menu, MenuInflater inflater) ประเภทบูลีนจะไม่ทำงาน
Bahaa Hany

15
หากคุณกำลังใช้Toolbarในรูปแบบกิจกรรมของคุณตรวจสอบให้แน่ใจว่าคุณเรียกใช้setSupportActionBar(your_toolbar)ในกิจกรรมของคุณ มิฉะนั้นsetHasOptionsMenuจะไม่มีผล
artkoenig

คุณเป็นที่รักของฉัน :)
Qadir Hussain

30

หากคุณใช้ธีมที่ไม่รองรับ ActionBar ดังนั้น OnCreateOptionsMenu () จะไม่ถูกเรียกโดยอัตโนมัติแม้ว่าคุณจะเขียนโค้ด Java ทั้งหมดอย่างถูกต้องก็ตาม

คุณสามารถเปิด AndroidManifest.xml เปลี่ยนค่าของandroid: themeเป็น "@android: style / Theme.Holo.Light.DarkActionBar" หรือธีมอื่น ๆ ที่รองรับ ActionBar


ฉันกำลังใช้แถบเครื่องมือจากไลบรารีการสนับสนุนและ Theme.AppCompat.Light.NoActionBar เป็นธีมและฉันกำลังประสบปัญหาเดียวกัน ... ไม่มีเมนูตัวเลือกปรากฏขึ้น
..plz help

6
ฉันแก้ไขได้โดยโทรtoolbar.inflateMenu(R.menu.menu_custom);
Dhruvam Gupta

เพียงเรียกใช้ setSupportActionBar (mToolbar) ในกิจกรรมของคุณและ onCreateOptionsMenu ใน Fragments จะถูกเรียกโดยอัตโนมัติ
Kapitola

12

สิ่งนี้ได้ผลสำหรับฉัน

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    setHasOptionsMenu(true);
    View view = inflater.inflate(R.layout.sample, null);
}

11

นอกจากนี้ตรวจสอบให้แน่ใจว่าอินสแตนซ์ Toolbar ที่คุณกำลังส่งผ่านไป

setSupportActionBar(toolbar);

ในกิจกรรมของคุณไม่ใช่nullเพราะคุณจะไม่ได้รับข้อยกเว้นหากเป็นจริงnullและคุณจะเสียเวลาสองสามชั่วโมงเหมือนที่ฉันทำ

ฉันใช้ButterKnifeเพื่อเชื่อมโยงมุมมอง แต่บังเอิญวางไว้setSupportActionBar(toolbar)ก่อนที่ฉันจะโทรไปจริงๆButterKnife.bind()


1
Haris คุณยอดเยี่ยมมาก ขอบคุณสำหรับการแบ่งปัน! ฉันมีปัญหานี้แน่นอนเพราะฉันใช้ Kotlin และหลาย ๆ ครั้งคุณไม่ต้องใช้ findViewById ฯลฯ ... เพื่อให้ได้มุมมองที่คุณต้องการ
DWndrer

1

เพียงบอกกิจกรรมโฮสต์ว่าแฟรกเมนต์ของคุณมีเมนูตัวเลือกในตัวสร้าง

YourFragment สาธารณะ () {setHasOptionsMenu (true);}

แม้ว่ามันจะได้ผลสำหรับฉัน แต่ก็ท้อใจตามที่ระบุไว้ในความคิดเห็นของ @aldorain

โดยทั่วไปแอปพลิเคชันไม่ควรใช้ตัวสร้าง โค้ดแอ็พพลิเคชันอันดับหนึ่งสามารถรันโดยที่แฟรกเมนต์พร้อมใช้งานอยู่ใน onAttach (Activity) ซึ่งเป็นจุดที่แฟรกเมนต์เชื่อมโยงกับกิจกรรม

ดังนั้นให้ใส่ setHasOptionsMenu (true) ใน onCreateView () หรือ onAttach () แทน


คุณไม่ควรเขียนตัวสร้างของคุณเองสำหรับชิ้นส่วนที่กำหนดเอง
aldorain

1
developer.android.com/reference/android/app/Fragment.html tl; dr "โดยทั่วไปแอปพลิเคชันไม่ควรใช้ตัวสร้าง [Fragment]"
aldorain

0

ฉันมีธีมที่ไม่ได้ให้ AppBar โดยค่าเริ่มต้นและคุณกำลังใช้มุมมองแถบเครื่องมือเพื่อให้คุณลักษณะนี้แทนอย่าลืมเรียกใช้ setSupportActionBar (แถบเครื่องมือ) ในเมธอด onCreate () ของกิจกรรมที่โฮสต์ของคุณ เศษ

หลังจากนั้นให้เรียก setHasOptionsMenu (true) ในเมธอด onCreate () แฟรกเมนต์ของคุณ

:)


-2

ตั้งค่าsetHasOptionsMenu(true)ในonCreateView()วิธีการในส่วนย่อย

@Override

 public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) 
 {
    Viewroot=inflater.inflate(R.layout.fragment_client_requestfragment,container,false);
  hideKeyboard();
    getemail = getArguments().getString("email_id");
    Log.e("email_id from activity",getemail);
    setHasOptionsMenu(true);
    return root;
}

1
สวัสดีและยินดีต้อนรับสู่ SO โปรดอย่าโพสต์คำตอบแบบโค้ดอย่างเดียวที่ไม่มีการแสดงความคิดเห็นและมีรูปแบบไม่ถูกต้องเนื่องจากไม่ได้อธิบายถึงปัญหาที่อธิบายไว้ในคำถาม ตรวจสอบที่นี่สำหรับเคล็ดลับทั่วไปบางอย่างเกี่ยวกับสิ่งที่ถือว่าเป็นคำตอบที่ดี
Gero
โดยการใช้ไซต์ของเรา หมายความว่าคุณได้อ่านและทำความเข้าใจนโยบายคุกกี้และนโยบายความเป็นส่วนตัวของเราแล้ว
Licensed under cc by-sa 3.0 with attribution required.