首页 > 解决方案 > Android按钮的背景颜色会自动改变

问题描述

我从未见过像以前那样奇怪的错误,我正在将 viewpager 与 tablayout 链接,在 viewpager 内部有三个片段。

其中两个片段(假设片段 1 和 3)内部有一个按钮,它们的颜色都设置为“粉红色”。当我第一次加载应用程序时,它显示片段 1,此时按钮是粉红色的,但是,每当我切换到片段 3 时,按钮的背景颜色都会更改为“白色”,并且按钮的其他属性保持不变.

如果我切换到片段 2,则不会发生这种情况。但是,如果我切换到片段 3 一次,片段 1 和 3 的按钮在余下的生命周期中都具有白色背景。

有人可以告诉我这里发生了什么或可能导致这种情况的原因吗?我根本没有改变 Java 文件中按钮的样式。

MainActivity.java

public class MainActivity extends AppCompatActivity {

private ActivityMainBinding binding;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    binding = DataBindingUtil.setContentView(this, R.layout.activity_main);

    setUpWithViewPager(binding.viewPager);
    // setupWithViewPager is a built-in method for TabLayout, setting up this TabLayout with a ViewPager
    // The TabLayout will be automatically populated from the PagerAdapter's page titles. By doing that,
    // when the user tabs on the tab, the appropriate fragment will be shown in the ViewPager
    // TabLayout provides a horizontal layout to display tabs.
    // Without this line you can still swipe left/right to see all the pages, just cannot tab on the
    // tab to switch pages
    binding.tabLayout.setupWithViewPager(binding.viewPager);

    // This method sets the toolbar as the app bar for the activity
    setSupportActionBar(binding.toolbar);

    // change the fab icon when the page is changed
    binding.viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {
            changeFabIcon(position);
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    });
}

private void setUpWithViewPager(ViewPager viewPager) {
    // An inner class defined in MainActivity
    SectionsPagerAdapter adapter = new SectionsPagerAdapter(getSupportFragmentManager());
    adapter.addFragment(new ChatsFragment(), "Chats");
    adapter.addFragment(new StatusFragment(), "Status");
    adapter.addFragment(new CallsFragment(), "Calls");
    // We need 3 fragments
    viewPager.setAdapter(adapter);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // getMenuInflater is used to instantiate menu XML files into Menu objects.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
    switch (item.getItemId()) {
        case R.id.menu_search: Toast.makeText(this, "Action Search", Toast.LENGTH_SHORT).show(); break;
        case R.id.menu_more: Toast.makeText(this, "Action More", Toast.LENGTH_SHORT).show(); break;
    }

    return super.onOptionsItemSelected(item);
}

private void changeFabIcon(final int index) {
    binding.fabAction.hide();

    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            switch (index) {
                case 0: binding.fabAction.setImageDrawable(getDrawable(R.drawable.ic_baseline_chat_24)); break;
                case 1: binding.fabAction.setImageDrawable(getDrawable(R.drawable.ic_baseline_camera_alt_24)); break;
                case 2: binding.fabAction.setImageDrawable(getDrawable(R.drawable.ic_baseline_call_24)); break;

            }
            binding.fabAction.show();
        }
    }, 400);
}

private static class SectionsPagerAdapter extends FragmentPagerAdapter {

    private final List<Fragment> mFragmentList = new ArrayList<>();
    private final List<String> mFragmentTitleList = new ArrayList<>();

    public SectionsPagerAdapter(@NonNull FragmentManager fm) {
        super(fm);
    }

    @NonNull
    @Override
    public Fragment getItem(int position) {
        return mFragmentList.get(position);
    }

    @Nullable
    @Override
    public CharSequence getPageTitle(int position) {
        return mFragmentTitleList.get(position);
    }

    @Override
    public int getCount() {
        return mFragmentList.size();
    }

    public void addFragment(Fragment fragment, String title) {
        mFragmentList.add(fragment);
        mFragmentTitleList.add(title);
    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>

<layout
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">
<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".view.MainActivity">

    <com.google.android.material.appbar.AppBarLayout
        android:id="@+id/app_bar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/colorPrimary">

        <androidx.appcompat.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="50dp"
            app:titleTextColor="@android:color/white"
            app:title="PepperChat"/>

    </com.google.android.material.appbar.AppBarLayout>

    <com.google.android.material.tabs.TabLayout
        android:id="@+id/tab_layout"
        android:layout_below="@+id/app_bar"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        app:tabBackground="@color/colorPrimary"
        app:tabGravity="fill"
        app:tabIndicator="@color/colorPrimary"
        app:tabIndicatorHeight="3dp"
        app:tabIndicatorColor="@android:color/white"
        app:tabSelectedTextColor="@android:color/white"
        app:tabTextColor="@android:color/white">

    </com.google.android.material.tabs.TabLayout>

    <androidx.viewpager.widget.ViewPager
        android:id="@+id/view_pager"
        android:layout_below="@id/tab_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:visibility="visible"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/fab_action"
        android:src="@android:drawable/stat_notify_chat"
        android:tint="@android:color/white"
        app:backgroundTint="@color/colorPrimary"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentEnd="true"
        android:layout_margin="15dp"/>

</RelativeLayout>
</layout>

片段调用.xml

<?xml version="1.0" encoding="utf-8"?>
<layout>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".menu.CallsFragment">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

    <LinearLayout
        android:id="@+id/ln_invite"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:layout_marginTop="30dp"
        android:orientation="vertical">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Invite your friends"
            android:textSize="25dp"
            android:textColor="@android:color/black"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:layout_marginBottom="20dp"
            android:textColor="@color/colorPrimary"
            android:gravity="center_horizontal"
            android:text="Name of your contact are using PepperChat.\nUse the bottom below to invite them."/>

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/colorPrimary"
            android:textColor="@android:color/black"
            android:layout_marginStart="30dp"
            android:layout_marginEnd="30dp"
            android:text="Invite a friend"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:layout_marginBottom="20dp"
            android:gravity="center_horizontal"
            android:text="Chat with your friends who are using PepperChat on iphone,\nAndroid or KaiOS phone"/>

    </LinearLayout>

</FrameLayout>
</layout>

片段聊天.xml

<?xml version="1.0" encoding="utf-8"?>
<layout>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".menu.ChatsFragment">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_height="match_parent"
        android:layout_width="match_parent"/>

    <LinearLayout
        android:id="@+id/ln_invite"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:layout_marginTop="30dp"
        android:orientation="vertical">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Invite your friends"
            android:textSize="25dp"
            android:textColor="@android:color/black"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:layout_marginBottom="20dp"
            android:textColor="@color/colorPrimary"
            android:gravity="center_horizontal"
            android:text="Name of your contact are using PepperChat.\nUse the bottom below to invite them."/>

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/colorPrimary"
            android:textColor="@android:color/black"
            android:layout_marginStart="30dp"
            android:layout_marginEnd="30dp"
            android:text="Invite a friend"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:layout_marginBottom="20dp"
            android:gravity="center_horizontal"
            android:text="Chat with your friends who are using PepperChat on iphone,\nAndroid or KaiOS phone"/>

    </LinearLayout>

</FrameLayout>
</layout>

标签: javaandroidandroid-studioandroid-fragments

解决方案


在两个 xml 文件中添加以下行后,按钮正常显示,但不知道为什么,有人可以解释发生了什么吗?(这与我使用的主题有关吗?)

android:backgroundTint="@color/colorPrimary"

我的主题是

<style name="Theme.PepperChat" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Primary brand color. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>

如果我将父级更改为 Theme.MaterialComponent.Light.NoActionBar,则应用程序可以正常工作而无需添加 backgroundTint。再次,想解释一下为什么会发生这种情况。


推荐阅读