【问题标题】:Cannot resolve method getActivity() in a class extending FragmentActivity无法解析扩展 FragmentActivity 的类中的方法 getActivity()
【发布时间】:2023-03-27 08:02:01
【问题描述】:

我在一个需要自定义工具栏的类中扩展了 Fragment Activity。因此,我添加了获取工具栏的代码,但 setSupportActionBar(toolbar) 不起作用。然后,我添加了 AppCompatActivity.getActivity() 进行转换,但效果不佳。

这里是代码 -

public class main_fragment extends FragmentActivity implements FragmentDrawer.FragmentDrawerListener {
private Toolbar toolbar;
private FragmentDrawer drawerFragment;


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

    toolbar = (Toolbar) findViewById(R.id.tool_bar);
    ((AppCompatActivity) getActivity()).setSupportActionBar(toolbar);
    ((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayShowHomeEnabled(true);

    drawerFragment = (FragmentDrawer)
            getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
    drawerFragment.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), toolbar);
    drawerFragment.setDrawerListener(this);

}

【问题讨论】:

  • 我试过了。没用。它显示无法解析“ActionBarCompat”的符号。

标签: android fragment android-fragmentactivity android-toolbar


【解决方案1】:

AppCompatActivity 扩展 FragmentActivity。你必须改变的第一件事是

extends FragmentActivity

extends AppCompatActivity

getActivity()Fragment 的一个方法。 Activity没有那个方法,所以你不需要调用它来使用setSupportActionBargetSupportActionBar

setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);

【讨论】:

  • 成功了!非常感谢!
【解决方案2】:

这是设置工具栏的Material方式。 1/ 在 XML 中声明它。 2/ 在你的活动/片段类中充气后找到它。 3/ 配置标题、菜单等。

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

</android.support.design.widget.AppBarLayout>
</android.support.design.widget.CoordinatorLayout>

在您的片段/活动中找到工具栏。

mToolbar = (Toolbar) view.findViewById(R.id.toolbar);
mToolbar.setTitle(/*your title*/);
mToolbar.inflateMenu(/* menu res id here*/);
mToolbar.setOnMenuItemClickListener(new OnMenuItemClickLister(/*override the click methods with item.getId == your id*/));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-18
    • 1970-01-01
    • 2011-12-31
    • 1970-01-01
    • 1970-01-01
    • 2021-08-28
    • 2017-09-30
    • 2017-07-09
    相关资源
    最近更新 更多