Android 从片段内部更改SupportActionBar?

Android 从片段内部更改SupportActionBar?,android,android-fragments,Android,Android Fragments,我刚在谷歌上搜索了“setsupportactionbar片段”,但我只找到了“getsupportactionbar from fragment”。这两者是相似的,还是有什么特别的地方?是的,这是相似的,但您必须记住,如果要使用片段布局文件的元素,必须将setSupportActionBar()放在onCreateView中: .. public class FragmentOne extends Fragment { .. @Override public void

我刚在谷歌上搜索了“setsupportactionbar片段”,但我只找到了“getsupportactionbar from fragment”。这两者是相似的,还是有什么特别的地方?

是的,这是相似的,但您必须记住,如果要使用片段布局文件的元素,必须将
setSupportActionBar()
放在
onCreateView
中:

..
public class FragmentOne extends Fragment {
    ..
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_one, container, false);

        Toolbar toolbar = view.findViewById(R.id.toolbar);
        ((AppCompatActivity) getActivity()).setSupportActionBar(toolbar);

        return view;
    }
    ..
}

您不应该在片段中使用
setSupportActionBar()
。因为每次在活动中添加此片段时,都会创建一个新的工具栏实例。所以每次屏幕上显示新工具栏时。所以这不是一个好办法。

我知道。对于我来说,用另一个工具栏替换它很重要。我有一个NavigationDrawer+工具栏。如果该抽屉中的特殊项目被称为工具栏,则该工具栏将被隐藏,并将新工具栏设置为supportactionbar。我正在使用它。你说的新工具栏是什么意思。我已经说过,对于一个活动,只有一个工具栏实例,我们可以转移到私人聊天吗?