簡體   English   中英

如何在Android中獲取Fragment的Activity的工具欄

[英]How to get toolbar of an Activity of the Fragment in Android

Android Fragment 相關查詢我們如何使用在fragment 內的fragmentActivty 中存在的工具欄,我們在framelayout 中的activity 中替換它

你可以嘗試這樣的事情:

Toolbar toolbar = getActivity().findViewById(R.id.toolbar);

或者

Toolbar toolbar = getParentFragment().findViewById(R.id.toolbar);

取決於你的情況。

我只是注意到你正在使用FragmentActivity

在 Google 文檔中找到的FragmentActivity重要信息( 鏈接):

Note: If you want to implement an activity that includes an action bar, you
should instead use the ActionBarActivity class, which is a subclass of this
one, so allows you to use Fragment APIs on API level 7 and higher.

如果您使用兼容性庫,那么您將需要擴展AppCompatActivity ( link )

查看這些類的繼承層次結構,它們都有FragmentActivity / android.support.v4.app.FragmentActivity作為父類。 這也可能是您的問題。


原答案:

您可以將Activity的引用傳遞給Fragment ,然后在那里獲取對Toolbar的引用,例如:

在您的活動中:

// 'this' being the activity context
MyFragment theFragment = new MyFragment(this);

在你的片段中:

// in fragment, use the reference passed in the constructor
myActivityReference.setActionBarTitle("My Title");

// or do this
Toolbar theToolbar = myActivityReference.getSupportActionBar();
theToolbar.doTheThingsIWant(...);

或者

您可以在片段中使用getActivity()方法並將其轉換為您的活動:

Toolbar theToolbar = ((MyActivity)getActivity()).getSupportActionBar();

我不確定是否需要演員……我不記得了。 如果您願意,請嘗試不使用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM