【问题标题】:Can i change title of my toolbar in my constructor if yes then how can it possible?如果可以,我可以在构造函数中更改工具栏的标题,那怎么可能?
【发布时间】:2016-03-29 15:42:35
【问题描述】:

如果可以,我可以在构造函数中更改工具栏的标题,那怎么可能?

public DashboardFragment() {


((AppCompatActivity) this.getActivity()).getSupportActionBar().setTitle("DashBoard");
}

【问题讨论】:

  • 您应该在 onCreate() 或之后更改标题
  • 但是我想根据我的代码改变构造函数。
  • 如果你的fragment嵌入在xml布局中,构造函数会在activity初始化之前运行,那么你会得到一个空指针异常。
  • 如果 Fragment 尚未附加,对 getActivity() 的调用可能会返回 null。所以在构造函数中调用 getActivity 是行不通的。当您知道 Fragment 附加到 Activity 时,您应该调用它,例如在 onCreate 中。
  • 我知道这就是为什么我要求使用其他方法来更改我的标题,......

标签: android android-studio fragment android-studio-2.0


【解决方案1】:

假设您在 Activity 的 xml 中定义了一个 Toolbar,您可以使用以下方法从 Fragment 访问它:

重写 Fragment 中的 onAttach() 方法,以便在父 Activity 可用时获取对它的引用。然后,只需获取您对工具栏的引用(应在您的活动 xml 中定义)并简单地设置标题。像这样……

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    Toolbar toolbar = (Toolbar) activity.findViewById(R.id.toolbar);
    toolbar.setTitle("Your Custom Title");
}

【讨论】:

    猜你喜欢
    • 2014-07-13
    • 1970-01-01
    • 2016-12-24
    • 1970-01-01
    • 1970-01-01
    • 2012-05-31
    • 1970-01-01
    • 2011-02-06
    • 1970-01-01
    相关资源
    最近更新 更多