简体   繁体   中英

How to change text color of one tab in Tab Layout View Pager android

I have only two tabs in tabLayout say Objectives and Students. Now, I want the color of students text to be grey till i check the objectives checkbox. After i have checked the checkbox, the colour of students text should change from grey to white. Below is the image of tabs :- 图片1

this is image 2

图片2

Following is the code for TabLayout :-

public class AllKPIActivity extends AppCompatActivity {

    private Toolbar toolbar;
    private TabLayout tabLayout;
    private ViewPagerAdapter adapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_objective_student);


        toolbar = (Toolbar) findViewById(R.id.toolbar);


        viewPager = (CustomViewPager) findViewById(R.id.viewpager);
        viewPager.setPagingEnabled(false);
        adapter = new ViewPagerAdapter(getSupportFragmentManager());
        setupViewPager(viewPager);

        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {


            }

            @Override
            public void onPageSelected(int position) {
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }

        });

        tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);


    private void setupViewPager(ViewPager viewPager) {
        adapter.addFragment(new ObjectivesFragment(), "Objectives");
        adapter.addFragment(new StudentsFragment(), "Students");
        viewPager.setAdapter(adapter);
    }


}

class ViewPagerAdapter extends FragmentStatePagerAdapter {
    private final List<Fragment> mFragmentList = new ArrayList<>();
    private final List<String> mFragmentTitleList = new ArrayList<>();

    public ViewPagerAdapter(FragmentManager manager) {
        super(manager);
    }

    @Override
    public Fragment getItem(int position) {
        switch (position) {
            case 0:
                ObjectivesFragment allFragment = new ObjectivesFragment();
                Bundle bundle = new Bundle();
                bundle.putString("uuid", uuid);
                allFragment.setArguments(bundle);
                return allFragment;
            case 1:
                studentsFragment = new StudentsFragment();
                Bundle bundle_students = new Bundle();
                bundle_students.putString("uuid", uuid);
                studentsFragment.setArguments(bundle_students);
                return studentsFragment;
        }
        return mFragmentList.get(position);
    }

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

    @Override
    public int getItemPosition(Object object) {
        if (object instanceof UpdateableFragment) {
            ((UpdateableFragment) object).update(selectedChildList);
        } else if (object instanceof ObjectivesFragment) {
        }
        return super.getItemPosition(object);
    }

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

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


}

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 10 && resultCode == requestCode) {
            if (data != null) {
                String colorCode = data.getExtras().get("colorCode").toString();
                String judgementName = data.getExtras().get("judgementName").toString();
                int position = data.getIntExtra("position", 0);
                studentsFragment.onJudgementSelected(colorCode, judgementName, position);

            }
        } else if (requestCode == 1001) {
            if (data != null) {
                String fileName = data.getExtras().get("File Name").toString();
                int position = data.getIntExtra("position", 0);
                System.out.print(fileName);
                studentsFragment.onCameraResult(fileName, position);
            }

        } else if (requestCode == 11) {
            if (data != null) {
                File fileName = (File) data.getExtras().get("fileName");
                int position = data.getIntExtra("position", 0);
                studentsFragment.onNotesCreated(fileName, position);
            }
        } else if (requestCode == StudentAdapter.READ_REQUEST_PREVIEW_CODE) {

            if (data != null) {
                setResult(RESULT_OK, data);
            }

        } else if (requestCode == StudentAdapter.AVIARY_EDITOR_RESULT) {

            if (data != null) {
  /*          if (intent != null && mAdapter != null) {
                Bundle extra = intent.getExtras();
                if (extra != null && extra.getBoolean(Constants.EXTRA_OUT_BITMAP_CHANGED)) {
                    if (useInternalStorage()) {
                        onImageModified();
                    } else {
                        //the file is on the SD card and must be copied back to the internal
                        //file structure. We then delete the temp file on the SD card.
                        SharedExecutorService.getInstance().execute(new MainThreadRunnable() {
                            boolean success;

                            @Override
                            public void runOnBackground() {
                                success = mMediaManager.copyFromTemp(PreviewActivity.this,
                                        mAdapterPosition);
                            }

                            @Override
                            public void runOnMain() {
                                mMediaManager.clearTempFiles(PreviewActivity.this);
                                if (!success) {
                                    AndroidUtils.buildSimpleErrorDialog(PreviewActivity.this)
                                            .setMessage(R.string.preview_error).show();
                                    return;
                                }

                                onImageModified();
                            }
                        });
                        return;
                    }
                }
            }*/
            }

        }
    }
}

Try this code:

tabHost.setOnTabChangedListener(new OnTabChangeListener() {
    @Override
    public void onTabChanged (String tabId){

        for (int i = 0; i < tabHost.getTabWidget().getChildCount(); i++) {
            tabHost.getTabWidget().getChildAt(i).setBackgroundColor(Color.parseColor("#FF0000")); // unselected
            TextView tv = (TextView) tabhost.getTabWidget().getChildAt(i).findViewById(android.R.id.title); //Unselected Tabs
            tv.setTextColor(Color.parseColor("#ffffff"));
        }

        tabHost.getTabWidget().getChildAt(tabHost.getCurrentTab()).setBackgroundColor(Color.parseColor("#0000FF")); // selected
        TextView tv = (TextView) tabhost.getCurrentTabView().findViewById(android.R.id.title); //for

        //Selected Tab
        tv.setTextColor(Color.parseColor("#000000"))

    }
});

I achieved this by

in xml

<android.support.design.widget.TabLayout
    app:tabBackground="@drawable/tab_background"/>

while tab_background is a selector

<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:drawable="@color/tab_background_selected"
        android:state_selected="true" />

    <item android:drawable="@color/tab_background_unselected" />
</selector>

EDITED:

for text color the method is described here ( https://github.com/astuetz/PagerSlidingTabStrip/issues/141 )

private LinearLayout mTabsLinearLayout;

@Override
public void onPageScrolled(int i, float v, int i2) {
    //overriden method not used
}

@Override
public void onPageSelected(int position) {
    for (int i = 0; i < mTabsLinearLayout.getChildCount(); i++) {
        TextView tv = (TextView) mTabsLinearLayout.getChildAt(i);
        if (i == position) {
            tv.setTextColor(Color.WHITE);
        } else {
            tv.setTextColor(Color.GREY);
        }
    }
}

@Override
public void onPageScrollStateChanged(int i) {
    //overriden method not used
}

use this when your are setting up tabstrip when the activity is created

public void setUpTabStrip() {

    //your other customizations related to tab strip
    // Set first tab selected
    mTabsLinearLayout = ((LinearLayout) tabStrip.getChildAt(0));
    for (int i = 0; i < mTabsLinearLayout.getChildCount(); i++) {
        TextView tv = (TextView) mTabsLinearLayout.getChildAt(i);

        if (i == 0) {
            tv.setTextColor(Color.WHITE);
        } else {
            tv.setTextColor(Color.GREY);
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM