要在Android中创建具有不同颜色的水平标签,您可以使用TabLayout和TabItem来实现。以下是一个示例代码:
TabLayout tabLayout = findViewById(R.id.tab_layout);
ViewPager viewPager = findViewById(R.id.view_pager);
TabAdapter adapter = new TabAdapter(getSupportFragmentManager());
adapter.addFragment(new Fragment1(), "Tab 1");
adapter.addFragment(new Fragment2(), "Tab 2");
adapter.addFragment(new Fragment3(), "Tab 3");
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
public class TabAdapter extends FragmentPagerAdapter {
private List fragmentList = new ArrayList<>();
private List fragmentTitleList = new ArrayList<>();
public TabAdapter(FragmentManager fm) {
super(fm);
}
public void addFragment(Fragment fragment, String title) {
fragmentList.add(fragment);
fragmentTitleList.add(title);
}
@Override
public Fragment getItem(int position) {
return fragmentList.get(position);
}
@Override
public int getCount() {
return fragmentList.size();
}
@Override
public CharSequence getPageTitle(int position) {
return fragmentTitleList.get(position);
}
}
public class Fragment1 extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_layout, container, false);
TextView textView = view.findViewById(R.id.tab_text);
textView.setText("Fragment 1");
textView.setBackgroundColor(getResources().getColor(R.color.colorFragment1));
return view;
}
}
public class Fragment2 extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_layout, container, false);
TextView textView = view.findViewById(R.id.tab_text);
textView.setText("Fragment 2");
textView.setBackgroundColor(getResources().getColor(R.color.colorFragment2));
return view;
}
}
public class Fragment3 extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_layout, container, false);
TextView textView = view.findViewById(R.id.tab_text);
textView.setText("Fragment 3");
textView.setBackgroundColor(getResources().getColor(R.color.colorFragment3));
return view;
}
}
确保在res/values/colors.xml文件中定义了颜色资源,例如:
#3F51B5
#FF0000
#00FF00
#0000FF
这样,您就可以创建具有不同颜色的水平标签了。
上一篇:Android设备:无法访问/proc/[PID]/status。
下一篇:Android设计师TextInputLayout渲染问题:java.lang.IllegalArgumentException:weight不在[0,1000]范围内。