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

时间:2016-02-09 18:57:34

标签: android android-tablayout

我是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>

对于每个选定的标签单个图像,我需要这样,每个标签都会显示一个图像。 here my image

1 个答案:

答案 0 :(得分:2)

您可以使用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
         }
     }
 });
相关问题