更改片段上的工具栏颜色

问题描述 投票:0回答:3

当选择菜单时,我一直在尝试更改工具栏颜色。我正在使用Fragment,我已经在堆栈溢出中阅读了很多解决方案,但它们似乎都没有工作。知道我做错了什么吗?

我正在尝试使用MainActivity类的onNavigationItemSelected()切换颜色。

到目前为止,我只能更改导航栏和状态栏的颜色,而不能更改工具栏或标签栏。

enter image description here

如果需要更多信息,只需要它!谢谢!

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$1.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$1.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$1.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$1.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)

除了错误之外,我还收到有关“使用或覆盖已弃用的API”的警告。我有什么想法我做错了吗?

android android-fragments android-toolbar android-navigation-drawer
3个回答
0
投票

您可以将此行添加到您的活动中

toolbar.setBackgroundColor(getResources().getColor(R.color.green));


0
投票

您的代码中存在问题。给你的工具栏类范围而不是方法。在updateToolbar()方法之外声明NavigationView和drawyer布局时声明工具栏。

Toolbar toolbar;

然后像这样初始化它:

toolbar = findViewById(R.id.toolbar);

然后你就可以改变颜色了:

toolbar.setBackgroundColor(getResources().getColor(R.color.green));

0
投票

如果片段上有空格,请在片段内添加工具栏,并将活动主题用作Appcompat.noactionbar。不要使用活动工具栏。这是一项更长的任务。此外,如果您想在工具栏中添加一些功能,从片段到向活动工具栏添加功能将会有点困难。

捷径: - 为1个片段使用1个工具栏,并记住您正在使用哪种工具栏。 Android支持版工具栏或常规工具栏

© www.soinside.com 2019 - 2024. All rights reserved.