更改片段上的工具栏颜色
Change toolbar color on fragment
我一直在尝试在选择菜单时更改工具栏颜色。我正在使用 Fragment,我在这里阅读了很多关于堆栈溢出的解决方案,但其中 none 似乎有效。知道我做错了什么吗?
我正在尝试使用 MainActivity 的 onNavigationItemSelected() 开关更改颜色 class。
到目前为止,我只能更改导航栏和状态栏的颜色,不能更改工具栏或标签栏。
如果需要更多信息,请索取!谢谢!
MainActivity.class
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
DrawerLayout drawerLayout;
NavigationView navigationView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
drawerLayout = findViewById(R.id.drawer_layout);
navigationView = findViewById(R.id.navigation_view);
if (navigationView != null)
navigationView.setNavigationItemSelectedListener(this);
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new AppBarMainFragment())
.commit();
updateToolbar(getString(R.string.perfil));
}
public void updateToolbar(String title) {
Toolbar toolbar = findViewById(R.id.toolbar);
if (toolbar != null)
toolbar.setTitle(title);
setSupportActionBar(toolbar);
ActionBarDrawerToggle toogle = new ActionBarDrawerToggle(this, drawerLayout, toolbar,
R.string.open_drawer, R.string.close_drawer);
drawerLayout.addDrawerListener(toogle);
toogle.syncState();
}
@Override
public boolean onNavigationItemSelected(MenuItem item) {
int itemId = item.getItemId();
LinearLayout rl = findViewById(R.id.header_wrapper);
// AppBarLayout abl = findViewById(R.id.fragTabs_Background); Do not work
// Integer colorTo = getResources().getColor(R.color.colorFacebook); Do not work
Fragment fragment = null;
switch (itemId) {
case R.id.nav_home:
fragment = new AppBarMainFragment();
break;
case R.id.nav_facebook:
BaseViewPagerAdapter adapter = new BaseViewPagerAdapter(
getSupportFragmentManager(), new String[] {"Siguiendo", "Seguidores"});
fragment = AppBarMainWithTabsFragment.getInstance(adapter, getString(R.string.facebook));
// setActionBar(getSupportActionBar().setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.colorFacebook))));
// abl.setBackground(new ColorDrawable(getResources().getColor(R.color.colorFacebook)));
rl.setBackgroundColor(getResources().getColor(R.color.colorFacebook));
if (Build.VERSION.SDK_INT >= 21){
getWindow().setNavigationBarColor(getResources().getColor(R.color.colorFacebook));
getWindow().setStatusBarColor(getResources().getColor(R.color.colorDarkFacebook));
}
break;
case R.id.nav_twitter:
BaseViewPagerAdapter adapter1 = new BaseViewPagerAdapter(
getSupportFragmentManager(), new String[] {"Recomendadas", "Miembro", "Tuyas"});
fragment = AppBarMainWithTabsFragment.getInstance(adapter1, getString(R.string.twitter));
break;
case R.id.nav_instagram:
View view = findViewById(android.R.id.content);
Snackbar.make(view, "Se ha pulsado para abrir las configuraciones.", Snackbar.LENGTH_LONG).show();
break;
}
if (fragment != null) {
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, fragment)
.commit();
}
drawerLayout.closeDrawer(GravityCompat.START);
return true;
}
}
片段
public class AppBarMainWithTabsFragment extends Fragment {
private BaseViewPagerAdapter adapter;
private String title;
public static AppBarMainWithTabsFragment getInstance(BaseViewPagerAdapter adapter, String title) {
AppBarMainWithTabsFragment fragment = new AppBarMainWithTabsFragment();
fragment.adapter = adapter;
fragment.title = title;
return fragment;
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.app_bar_main_with_tabs, container, false);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
ViewPager viewPager = view.findViewById(R.id.view_pager);
viewPager.setAdapter(adapter);
TabLayout tabLayout = view.findViewById(R.id.tab_layout);
tabLayout.setupWithViewPager(viewPager);
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
MainActivity mainActivity = (MainActivity) getActivity();
mainActivity.updateToolbar(title);
}
}
布局 这是带有选项卡的 barTool 的布局
<?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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<android.support.design.widget.AppBarLayout
android:id="@+id/fragTabs_Background"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay" />
<android.support.design.widget.TabLayout
android:id="@+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="@+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="?attr/actionBarSize"
app:layout_behavior="@string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>
更新
我在评论中阅读了 Nilesh Rathod 建议的解决方案,但我不明白如何实施。
我刚刚尝试了 Hardik Kanak 在评论中建议的解决方案,但我遇到了这个错误
--------- beginning of crash
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.socialhub, PID: 9027
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.setBackgroundDrawable(android.graphics.drawable.Drawable)' on a null object reference
at com.example.socialhub.MainActivity.onNavigationItemSelected(MainActivity.java:80)
at android.support.design.widget.NavigationView.onMenuItemSelected(NavigationView.java:170)
at android.support.v7.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:840)
at android.support.v7.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:158)
at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:991)
at android.support.design.internal.NavigationMenuPresenter.onClick(NavigationMenuPresenter.java:352)
at android.view.View.performClick(View.java:5280)
at android.view.View$PerformClick.run(View.java:21239)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:234)
at android.app.ActivityThread.main(ActivityThread.java:5526)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Application terminated.
我也试过 Mohamad Mahdi Farzaneh 的解决方案,但我得到这个错误:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.socialhub, PID: 14964
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.setBackgroundDrawable(android.graphics.drawable.Drawable)' on a null object reference
at com.example.socialhub.MainActivity.onNavigationItemSelected(MainActivity.java:80)
at android.support.design.widget.NavigationView.onMenuItemSelected(NavigationView.java:170)
at android.support.v7.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:840)
at android.support.v7.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:158)
at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:991)
at android.support.design.internal.NavigationMenuPresenter.onClick(NavigationMenuPresenter.java:352)
at android.view.View.performClick(View.java:5280)
at android.view.View$PerformClick.run(View.java:21239)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:234)
at android.app.ActivityThread.main(ActivityThread.java:5526)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
除了错误之外,我还收到有关 "uses or overrides a deprecated API" 的警告。知道我做错了什么吗?
您可以将此行添加到您的 activity
toolbar.setBackgroundColor(getResources().getColor(R.color.green));
你的代码有问题。
给你的工具栏 class 范围而不是方法。在 updateToolbar() 方法之外声明 NavigationView 和抽屉布局时声明工具栏。
Toolbar toolbar;
然后像这样初始化它:
toolbar = findViewById(R.id.toolbar);
然后你就可以改变颜色了:
toolbar.setBackgroundColor(getResources().getColor(R.color.green));
如果片段上有 space,请在片段内添加工具栏并使用 activity 主题作为 Appcompat.noactionbar。
不要使用 activity 的工具栏。这是一项更长的任务。此外,如果您想在工具栏内添加一些功能,从片段到向 activity 工具栏添加功能会有点困难。
快捷方式:- 对 1 个片段使用 1 个工具栏,并记住您使用的是哪种工具栏。 Android支持版本工具栏或常规工具栏
我一直在尝试在选择菜单时更改工具栏颜色。我正在使用 Fragment,我在这里阅读了很多关于堆栈溢出的解决方案,但其中 none 似乎有效。知道我做错了什么吗?
我正在尝试使用 MainActivity 的 onNavigationItemSelected() 开关更改颜色 class。
到目前为止,我只能更改导航栏和状态栏的颜色,不能更改工具栏或标签栏。
如果需要更多信息,请索取!谢谢!
MainActivity.class
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
DrawerLayout drawerLayout;
NavigationView navigationView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
drawerLayout = findViewById(R.id.drawer_layout);
navigationView = findViewById(R.id.navigation_view);
if (navigationView != null)
navigationView.setNavigationItemSelectedListener(this);
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new AppBarMainFragment())
.commit();
updateToolbar(getString(R.string.perfil));
}
public void updateToolbar(String title) {
Toolbar toolbar = findViewById(R.id.toolbar);
if (toolbar != null)
toolbar.setTitle(title);
setSupportActionBar(toolbar);
ActionBarDrawerToggle toogle = new ActionBarDrawerToggle(this, drawerLayout, toolbar,
R.string.open_drawer, R.string.close_drawer);
drawerLayout.addDrawerListener(toogle);
toogle.syncState();
}
@Override
public boolean onNavigationItemSelected(MenuItem item) {
int itemId = item.getItemId();
LinearLayout rl = findViewById(R.id.header_wrapper);
// AppBarLayout abl = findViewById(R.id.fragTabs_Background); Do not work
// Integer colorTo = getResources().getColor(R.color.colorFacebook); Do not work
Fragment fragment = null;
switch (itemId) {
case R.id.nav_home:
fragment = new AppBarMainFragment();
break;
case R.id.nav_facebook:
BaseViewPagerAdapter adapter = new BaseViewPagerAdapter(
getSupportFragmentManager(), new String[] {"Siguiendo", "Seguidores"});
fragment = AppBarMainWithTabsFragment.getInstance(adapter, getString(R.string.facebook));
// setActionBar(getSupportActionBar().setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.colorFacebook))));
// abl.setBackground(new ColorDrawable(getResources().getColor(R.color.colorFacebook)));
rl.setBackgroundColor(getResources().getColor(R.color.colorFacebook));
if (Build.VERSION.SDK_INT >= 21){
getWindow().setNavigationBarColor(getResources().getColor(R.color.colorFacebook));
getWindow().setStatusBarColor(getResources().getColor(R.color.colorDarkFacebook));
}
break;
case R.id.nav_twitter:
BaseViewPagerAdapter adapter1 = new BaseViewPagerAdapter(
getSupportFragmentManager(), new String[] {"Recomendadas", "Miembro", "Tuyas"});
fragment = AppBarMainWithTabsFragment.getInstance(adapter1, getString(R.string.twitter));
break;
case R.id.nav_instagram:
View view = findViewById(android.R.id.content);
Snackbar.make(view, "Se ha pulsado para abrir las configuraciones.", Snackbar.LENGTH_LONG).show();
break;
}
if (fragment != null) {
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, fragment)
.commit();
}
drawerLayout.closeDrawer(GravityCompat.START);
return true;
}
}
片段
public class AppBarMainWithTabsFragment extends Fragment {
private BaseViewPagerAdapter adapter;
private String title;
public static AppBarMainWithTabsFragment getInstance(BaseViewPagerAdapter adapter, String title) {
AppBarMainWithTabsFragment fragment = new AppBarMainWithTabsFragment();
fragment.adapter = adapter;
fragment.title = title;
return fragment;
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.app_bar_main_with_tabs, container, false);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
ViewPager viewPager = view.findViewById(R.id.view_pager);
viewPager.setAdapter(adapter);
TabLayout tabLayout = view.findViewById(R.id.tab_layout);
tabLayout.setupWithViewPager(viewPager);
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
MainActivity mainActivity = (MainActivity) getActivity();
mainActivity.updateToolbar(title);
}
}
布局 这是带有选项卡的 barTool 的布局
<?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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<android.support.design.widget.AppBarLayout
android:id="@+id/fragTabs_Background"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay" />
<android.support.design.widget.TabLayout
android:id="@+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="@+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="?attr/actionBarSize"
app:layout_behavior="@string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>
更新
我在评论中阅读了 Nilesh Rathod 建议的解决方案,但我不明白如何实施。
我刚刚尝试了 Hardik Kanak 在评论中建议的解决方案,但我遇到了这个错误
--------- beginning of crash
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.socialhub, PID: 9027
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.setBackgroundDrawable(android.graphics.drawable.Drawable)' on a null object reference
at com.example.socialhub.MainActivity.onNavigationItemSelected(MainActivity.java:80)
at android.support.design.widget.NavigationView.onMenuItemSelected(NavigationView.java:170)
at android.support.v7.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:840)
at android.support.v7.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:158)
at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:991)
at android.support.design.internal.NavigationMenuPresenter.onClick(NavigationMenuPresenter.java:352)
at android.view.View.performClick(View.java:5280)
at android.view.View$PerformClick.run(View.java:21239)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:234)
at android.app.ActivityThread.main(ActivityThread.java:5526)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Application terminated.
我也试过 Mohamad Mahdi Farzaneh 的解决方案,但我得到这个错误:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.socialhub, PID: 14964
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.setBackgroundDrawable(android.graphics.drawable.Drawable)' on a null object reference
at com.example.socialhub.MainActivity.onNavigationItemSelected(MainActivity.java:80)
at android.support.design.widget.NavigationView.onMenuItemSelected(NavigationView.java:170)
at android.support.v7.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:840)
at android.support.v7.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:158)
at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:991)
at android.support.design.internal.NavigationMenuPresenter.onClick(NavigationMenuPresenter.java:352)
at android.view.View.performClick(View.java:5280)
at android.view.View$PerformClick.run(View.java:21239)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:234)
at android.app.ActivityThread.main(ActivityThread.java:5526)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
除了错误之外,我还收到有关 "uses or overrides a deprecated API" 的警告。知道我做错了什么吗?
您可以将此行添加到您的 activity
toolbar.setBackgroundColor(getResources().getColor(R.color.green));
你的代码有问题。 给你的工具栏 class 范围而不是方法。在 updateToolbar() 方法之外声明 NavigationView 和抽屉布局时声明工具栏。
Toolbar toolbar;
然后像这样初始化它:
toolbar = findViewById(R.id.toolbar);
然后你就可以改变颜色了:
toolbar.setBackgroundColor(getResources().getColor(R.color.green));
如果片段上有 space,请在片段内添加工具栏并使用 activity 主题作为 Appcompat.noactionbar。 不要使用 activity 的工具栏。这是一项更长的任务。此外,如果您想在工具栏内添加一些功能,从片段到向 activity 工具栏添加功能会有点困难。
快捷方式:- 对 1 个片段使用 1 个工具栏,并记住您使用的是哪种工具栏。 Android支持版本工具栏或常规工具栏