如何在 android 中的选定选项卡上设置单独的背景图片

how to set individual background image on selected tab in android

我是 android 的新手,我想在选定的选项卡上显示单独的总背景,但我这样做是为了总背景,就像我在更改另一个选项卡时需要的一样 我需要每个选项卡的单独图像任何在我的代码下方帮助我的人,我需要为每个选项卡使用这张图片

XML布局:

 <LinearLayout
    android:id="@+id/main_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"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="vertical"
   android:background="@drawable/imag_bg" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:text="AppName"
            android:id="@+id/textView"
            android:textColor="#FFFFFF"
            android:textStyle="bold"

            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="150dp"
            android:textSize="55dp"
            android:layout_gravity="center_horizontal" />
        <android.support.design.widget.TabLayout
            android:id="@+id/tab_layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"

            android:background="?attr/colorPrimary"
            android:layout_marginTop="25dp"
            android:elevation="6dp"
            android:minHeight="?attr/actionBarSize"
            android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"/>

        <android.support.v4.view.ViewPager
            android:id="@+id/pager"
            android:layout_width="match_parent"
            android:layout_height="fill_parent"
            android:layout_below="@id/tab_layout"/>
</LinearLayout>

我需要为每个选定的标签单独的图像这样,我每个标签都得到一张图像。

您可以使用 ViewPager.onPageChangeListener 并相应地更改 main_layout 背景。

LinearLayout mMainLayout = findViewById(R.id.main_layout);//get the main_layout reference
ViewPager viewPager = findViewById(R.id.pager);//get the ViewPager reference

viewPager.setOnPageChangeListener(new OnPageChangeListener() {
     public void onPageScrollStateChanged(int state) {}
     public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}

     public void onPageSelected(int position) {
         //set the background according each tab/page
         if(position == 0){
            mMainLayout.setBackgroundResource(R.drawable.imag_bg);
         }else{
            mMainLayout.setBackgroundResource(R.drawable.image_2);//change to your alternative image
         }
     }
 });