标题,菜单项未显示在片段内的ActionBar上

时间:2017-01-17 16:44:44

标签: java android xml android-fragments

我在xml中添加了自定义工具栏,然后将其添加为片段中的Actionbar。 但它没有显示从标题到菜单的任何内容。唯一的操作栏是可见的

这是我的xml代码

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent">



    <!-- Must be last for right layering display -->
    <FrameLayout
        android:id="@+id/toolbar_container"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar2"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="@color/colorPrimary" />

    </FrameLayout>

</FrameLayout>

这是我的java代码

public class searchView extends Fragment{

    Toolbar search;
    MaterialSearchView search_view;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v =  inflater.inflate(R.layout.search_view,container,false);
        FrameLayout layout = (FrameLayout) inflater.inflate(R.layout.search_view, container, false);

        search = (Toolbar)layout.findViewById(R.id.toolbar2);
        ((AppCompatActivity) getActivity()).setSupportActionBar(search);
        ((AppCompatActivity) getActivity()).getSupportActionBar().setTitle("Contacts");
        setHasOptionsMenu(true);

        return v;
    }
}

在这些代码中,我在MainActivity On Bottombar上调用了片段,然后单击

  else if (position==1){
                    searchView f = new searchView();
                    getSupportFragmentManager().beginTransaction().replace(R.id.framelayout,f).commit();
                }
                return true;

1 个答案:

答案 0 :(得分:1)

Toolbar search;
MaterialSearchView search_view;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v =  inflater.inflate(R.layout.search_view,container,false);
    setHasOptionsMenu(true);
    search = (Toolbar)v.findViewById(R.id.toolbar2);
    ((AppCompatActivity) getActivity()).setSupportActionBar(search);
    ((AppCompatActivity) getActivity()).getSupportActionBar().setTitle("Contacts");

    return v;
}

}

显示选项菜单覆盖

 @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
    //add your  menu here;
    }