OnCreateOptionsMenu()不会调用片段 [英] OnCreateOptionsMenu() not called in Fragment

查看:136
本文介绍了OnCreateOptionsMenu()不会调用片段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


    我有得到了一个活性2片段水平放置一个应用程序。     
    在我的活动我虚增菜单使用onCreateOptionsMEnu()使用它我能动作条显示选项菜单。但是,当我尝试更新从我的一个片段,该onCreateoptionsmenu(操作栏菜单项)是不是called.So,我不能更新操作栏选项菜单。谁能帮我在设法解决这个问题。
    在code在我的活动如下:
    myActivity.java
    ===============

 包com.andr.androidtablelist;

进口java.io.IOException异常;

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

进口com.andr.fragments.ListLeftFragment;
进口com.andr.utils.DBHelper;

      公共类TabletActivity延伸活动{
    动作条动作条= NULL;

    @覆盖
    保护无效的onCreate(包savedInstanceState){
        super.onCreate(savedInstanceState);
        DBHelper dbhelper;
        dbhelper =新DBHelper(本);
        尝试 {
            dbhelper.createDatabase();
        }赶上(IOException异常前){
            ex.printStackTrace();
        }
        的setContentView(R.layout.activity_tablet);
        动作条= getActionBar();
        actionBar.setDisplayHomeAsUpEnabled(假);
        getFragmentManager()的BeginTransaction()
                .replace(R.id.master,ListLeftFragment.newInstance())提交()。
    }

    @覆盖
    公共布尔onCreateOptionsMenu(功能菜单){
        MenuInflater充气= getMenuInflater();
        inflater.inflate(R.menu.tablet,菜单);
        返回true;
    }

    @覆盖
    公共布尔onOptionsItemSelected(菜单项项){
        开关(item.getItemId()){
        案例android.R.id.home:
            Toast.makeText(
                    getApplicationContext(),
                    返回堆栈数:
                            + getFragmentManager()。getBackStackEntryCount(),
                    Toast.LENGTH_LONG).show();
            如果(getFragmentManager()。getBackStackEntryCount()== 1){
                actionBar.setDisplayHomeAsUpEnabled(假);
            }
            如果(getFragmentManager()getBackStackEntryCount()> 1){
                getFragmentManager()popBackStack()。

            }
            返回true;

        }
        返回super.onOptionsItemSelected(项目);
    }

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

< BR> myFragment.java
     ===============
      包com.andr.fragments;


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

进口com.andr.androidtablelist.R;
进口com.andr.helper.LazyHelper;

   公共类ListLeftFragment扩展片段{
    私有静态ListLeftFragment listFragment = NULL;

    公共静态ListLeftFragment的newInstance(){
        listFragment =新ListLeftFragment();
        返回listFragment;
    }

     @覆盖
    公共无效的onCreate(包savedInstanceState){
        // TODO自动生成方法存根
        super.onCreate(savedInstanceState);


    }

     @覆盖
    公共查看onCreateView(LayoutInflater充气,容器的ViewGroup,
            捆绑savedInstanceState){
         视图V = inflater.inflate(R.layout.fragment_listlayout,集装箱,假);
         。getActivity()invalidateOptionsMenu();
         ListView的LV =(ListView控件)v.findViewById(R.id.lview);
         的String []值=新的String [] {机器人,iPhone,WindowsMo​​bile的,
                    黑莓,WebOS的,Ubuntu的,Windows7的,最大OS X,
                    Linux的,OS / 2,Ubuntu的,Windows7的,最大OS X,Linux的,
                    OS / 2,Ubuntu的,Windows7的,最大OS X,Linux的,OS / 2,
                    机器人,iPhone,WindowsMo​​bile的};
         。getActivity()getActionBar()的setTitle(LeftList);

          ArrayList的<字符串>名单=新的ArrayList<字符串>();
         LazyHelper lHelper =新LazyHelper(getActivity());
         表= lHelper.getLazyDetials();

           / *的for(int i = 0; I< values​​.length ++我){
              list.add(值[I]);
            }
            最后StableArrayAdapter适配器=新StableArrayAdapter(getActivity()
                android.R.layout.simple_list_item_1,清单); * /
            LeftListAdapter lAdapter =新LeftListAdapter(getActivity(),清单);
            lv.setAdapter(lAdapter);
            lv.setOnItemClickListener(新OnItemClickListener()
            {

                @覆盖
                公共无效onItemClick(适配器视图<>为arg0,查看ARG1,
                        INT POS,长ARG3){
                    最后弦乐clickedData =(字符串)arg0.getItemAtPosition(POS);
                    束束=新包();
                    bundle.putString(clickedItemName,clickedData);
                    片段detailFragment = DetailFormRightFragment.newInstance();
                    detailFragment.setArguments(包);
                    。getActivity()getFragmentManager()的BeginTransaction()代替(R.id.details,detailFragment).addToBackStack(空).commit()。
                }

            }
                    );
         返回伏;
    }


     @覆盖
    公共无效onCreateOptionsMenu(功能菜单,MenuInflater充气){
        super.onCreateOptionsMenu(菜单,充气);
        。getActivity()getMenuInflater()膨胀(R.menu.search,菜单);
        搜索查看搜索查看=(搜索查看)menu.findItem(R.id.search);
        sea​​rchView.setIconifiedByDefault(真正的);
    }

     @覆盖
    公共布尔onOptionsItemSelected(菜单项项){

         super.onOptionsItemSelected(项目);
         返回false;
    }


     @覆盖
    公共无效prepareOptionsMenu(功能菜单)在{
         super.on prepareOptionsMenu(菜单);
        / *菜单项项目;
        menu.clear();
        。getActivity()getMenuInflater()膨胀(R.menu.search,菜单);
        搜索查看搜索查看=(搜索查看)menu.findItem(R.id.search);
        sea​​rchView.setIconifiedByDefault(真正的); * /
    }

     私有类StableArrayAdapter扩展ArrayAdapter<字符串> {

            HashMap的<字符串,整数> mIdMap =新的HashMap<字符串,整数>();

            公共StableArrayAdapter(上下文的背景下,INT textViewResourceId,
                名单<字符串>对象){
              超(背景下,textViewResourceId,对象);
              的for(int i = 0; I< objects.size(); ++ I){
                mIdMap.put(objects.get(ⅰ),ⅰ);
              }
            }

            @覆盖
            众长getItemId(INT位置){
              字符串项=的getItem(位置);
              返回mIdMap.get(项目);
            }

            @覆盖
            公共布尔hasStableIds(){
              返回true;
            }

          }

     LeftListAdapter扩展了BaseAdapter私有类实现OnClickListener {
         私人语境mcontext;
         ArrayList的<字符串>的ListData;
         私人LayoutInflater充气= NULL;
         公共LeftListAdapter(上下文的背景下,ArrayList的<字符串> listItems中){
              mcontext =背景;
              的ListData = listItems中;
              充气=(LayoutInflater)mcontext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
         }

        @覆盖
        公众诠释getCount将(){
            返回listData.size();
        }

        @覆盖
        公共对象的getItem(INT为arg0){
            返回null;
        }

        @覆盖
        众长getItemId(INT为arg0){
            // TODO自动生成方法存根
            返回0;
        }

        @覆盖
        公共查看getView(INT的立场,观点来看,一个ViewGroup ARG2){
            //创建一个ViewHolder参考
            查看VI =图。
            如果(六== NULL){
                VI = inflater.inflate(R.layout.item,NULL);
            }
            TextView的文字=(TextView的)vi.findViewById(R.id.text);
            text.setText(listData.get(位置));
            vi.setOnClickListener(本);
            返回六;
        }

        @覆盖
        公共无效的onClick(查看六){
            TextView的文字=(TextView的)vi.findViewById(R.id.text);
            束束=新包();
            bundle.putString(clickedItemName,text.getText()的toString());
            片段detailFragment = DetailFormRightFragment.newInstance();
            detailFragment.setArguments(包);
            。getActivity()getFragmentManager()的BeginTransaction()代替(R.id.details,detailFragment).addToBackStack(空).commit()。
        }

     }
   }
 

解决方案

在您片段的onCreateView()方法,你需要调用setHasOptionsMenu(真)告诉你的片段有想要添加菜单选项的主机活动。


I have an app which got one activity with 2 fragments placed horizontally.
In my activity I inflated menu using onCreateOptionsMEnu() using which I am able to display actionbar options menu. But when I try to update the action bar menu items from one of my fragment , the onCreateoptionsmenu() is not called.So,I'm not able to update the action bar options menu. Can anyone help me in sorting out this issue.
The code in my activity is as below:
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

<br> 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();          
        }

     }
   }

解决方案

In your fragment's onCreateView() method, you need to call setHasOptionsMenu(true) to tell the host activity that your fragment has menu options that it wants to add.

这篇关于OnCreateOptionsMenu()不会调用片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆