单击tabhost并在Android中更改片段时更改操作栏

问题描述 投票:0回答:1

当我单击tabhost和片段更改之一时,如何在活动中更改操作栏?

我的代码在下面。

MainActivity

public class MainActivity extends ActionBarActivity {

    private FragmentTabHost mTabHost;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.bottom_tabs);

        mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
        mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);

        Bundle b = new Bundle();
        b.putString("key", "Home");
        mTabHost.addTab(mTabHost.newTabSpec("home").setIndicator("Home",getResources().getDrawable(R.drawable.tab_one)),HomeFragment.class, b); 
        mTabHost.getTabWidget().getChildAt(0).setBackgroundColor(Color.parseColor("#D6D5D6"));
        TextView tv1 = (TextView) mTabHost.getTabWidget().getChildAt(0).findViewById(android.R.id.title); //Unselected Tabs
        tv1.setTextColor(Color.parseColor("#000000"));
    }

    @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);
        return true;
    }
}

HomeFragment

public class HomeFragment extends Fragment {

public HomeFragment() {
        // TODO Auto-generated constructor stub
    }

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

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        View v = LayoutInflater.from(getActivity()).inflate(R.layout.activity_home_fragment,
                null);

return v;
    }


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

@Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater)
    {
        super.onCreateOptionsMenu(menu, inflater);
        menu.clear();


        //fragment specific menu creation
    }
}
java android android-fragments
1个回答
0
投票

这是您的片段自动完成的。您应该添加

setHasOptionsMenu(true);

在您片段的onCreate()方法中。

[另外,您应该使用传递给onCreateView的LayoutInflater-您不需要通过活动再次获取它。

© www.soinside.com 2019 - 2024. All rights reserved.