Andorid之TabLayout+ViewPager
文章目录
- 前言
- 一、效果图
- 二、使用步骤
- 1.主xml布局
- 2.activity代码
- 3.MyTaskFragment代码
- 4.MyTaskFragment的xml布局
- 5.Adapter代码
- 6.item布局
- 总结
前言
TabLayout+ViewPager功能需求已经是常见功能了,我就不多解释了,需要的自取。
一、效果图
二、使用步骤
1.主xml布局
代码如下(示例):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"android:layout_width="match_parent"android:layout_height="match_parent"android:background="@color/backColor"android:orientation="vertical"><include layout="@layout/title_hslayout" /><LinearLayoutandroid:layout_width="match_parent"android:layout_height="44dp"android:background="#ffFFE7CB"android:gravity="center_vertical"android:orientation="horizontal"><ImageViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginLeft="15dp"android:src="@mipmap/ico_xlb" /><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginLeft="5dp"android:text="请勿恶意提交订单,被举报核实将面临封号封设备处罚!"android:textColor="#ff981c"android:textSize="13dp" /></LinearLayout><com.google.android.material.tabs.TabLayoutandroid:id="@+id/tablayout"android:layout_width="match_parent"android:layout_height="45dp"android:overScrollMode="never"app:tabIndicator="@mipmap/ico_jdt"app:tabIndicatorColor="#02C7AB"app:tabIndicatorFullWidth="false"app:tabMode="fixed"app:tabIndicatorHeight="4dp"app:tabRippleColor="@null"app:tabSelectedTextColor="#02C7AB"app:tabTextAppearance="@style/TabLayoutTextStyleys"app:tabTextColor="#66061C1A"></com.google.android.material.tabs.TabLayout><androidx.viewpager.widget.ViewPagerandroid:id="@+id/viewpager"android:layout_width="match_parent"android:layout_height="match_parent"android:overScrollMode="never" />
</LinearLayout>
2.activity代码
这里需要注意的是继承FragmentActivity()。
class MyTask : FragmentActivity(), View.OnClickListener {private lateinit var imag_fh: ImageViewprivate lateinit var text_title: TextViewprivate lateinit var tablayout: TabLayoutprivate lateinit var viewpager: ViewPagerprivate lateinit var titlelist: List<String>private lateinit var fragments: MutableList<Fragment>private lateinit var adapter: MyTaskAdapterprivate lateinit var message: Stringoverride fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)//去掉状态栏if (Build.VERSION.SDK_INT >= 21) {val decorView = window.decorViewval option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLEdecorView.systemUiVisibility = optionwindow.statusBarColor = Color.parseColor("#00000000")}setContentView(R.layout.mytask)initView()}fun initView() {fragments = mutableListOf()imag_fh = findViewById(R.id.imag_fh)text_title = findViewById(R.id.text_title)text_title.text = "我的任务"tablayout = findViewById(R.id.tablayout)viewpager = findViewById(R.id.viewpager)titlelist = listOf("待提交","审核中","已通过","未通过","复审中")for (i in titlelist.indices) {val fragment = MyTaskFragment()fragments.add(fragment)}adapter =MyTaskAdapter(fragments,titlelist,supportFragmentManager,this@MyTask)viewpager.adapter = adaptertablayout.setupWithViewPager(viewpager)tablayout.setSelectedTabIndicatorFixWidth(60f)tablayout.setSelectedTabIndicatorFixWidth(60f)//让tab充满屏幕
// tablayout.tabMode = TabLayout.MODE_FIXED;
// tablayout.tabGravity = TabLayout.GRAVITY_FILL;tablayout.addOnTabSelectedListener(object :TabLayout.OnTabSelectedListener {override fun onTabSelected(tab: TabLayout.Tab?) {handlerTabLayoutBold(tab, true)}override fun onTabUnselected(tab: TabLayout.Tab?) {handlerTabLayoutBold(tab, false)}override fun onTabReselected(tab: TabLayout.Tab?) {}})for (i in 0 until tablayout.tabCount) {val tab: TabLayout.Tab? = tablayout.getTabAt(i)if (tab != null) {tab.view.isLongClickable = falseif (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {tab.view.tooltipText = null // 或者设置空字符串 ""}}}imag_fh.setOnClickListener(this)}override fun onClick(v: View?) {when (v?.id) {R.id.imag_fh -> finish()}}/*** 设置指示符固定宽度*/fun TabLayout.setSelectedTabIndicatorFixWidth(width: Float) {setSelectedTabIndicator(object : DrawableWrapper(tabSelectedIndicator) {override fun setBounds(left: Int, top: Int, right: Int, bottom: Int) {var realLeft = leftvar realRight = rightif ((right - left).toFloat() != width) {val center = left + (right - left).toFloat() / 2realLeft = (center - width / 2).toInt()realRight = (center + width / 2).toInt()}super.setBounds(realLeft, top, realRight, bottom)}})}/** 修改单独某一个的粗细*/fun handlerTabLayoutBold(tab: TabLayout.Tab?, isBold: Boolean) {tab?.view?.forEach { view ->if (view is TextView) {if (isBold) {view.typeface = Typeface.DEFAULT_BOLD} else {view.typeface = Typeface.DEFAULT}}}}
}
3.MyTaskFragment代码
/*** @Author : CaoLiulang* @Time : 2025/5/10 11:27* @Description :待提交fragment*/
class MyTaskFragment() : Fragment(), OnClickListener {private var rootView: View? = nullprivate var firstLoad = falseprivate var isKeyboardVisible = falseprivate lateinit var fbrefresh: SmartRefreshLayout//刷新private lateinit var clssheader: ClassicsHeader//刷新头private lateinit var classicsfooter: ClassicsFooter//加载private var pageNum = 1private lateinit var list_view: RecyclerViewprivate lateinit var adapter: MyYSAdapter1private lateinit var list: MutableList<String>@Nullableoverride fun onCreateView(inflater: LayoutInflater,@Nullable container: ViewGroup?,@Nullable savedInstanceState: Bundle?): View? {firstLoad = true//视图创建完成,将变量置为truerootView = inflater.inflate(R.layout.mytaskfragment, container, false)return rootView}override fun onViewCreated(view: View, savedInstanceState: Bundle?) {super.onViewCreated(view, savedInstanceState)list = mutableListOf()for (i in 1..10) {list.add("任务名称$i")}clssheader = ClassicsHeader(requireActivity())classicsfooter = ClassicsFooter(requireActivity())fbrefresh = rootView!!.findViewById(R.id.fbrefresh)fbrefresh.isEnableRefresh = true //是否启用下拉刷新fbrefresh.isEnableLoadMore = true //是否启用上拉加载功能//刷新fbrefresh.setOnRefreshListener {pageNum = 1}//加载fbrefresh.setOnLoadMoreListener {pageNum++}list_view = rootView!!.findViewById(R.id.list_view)list_view.layoutManager = LinearLayoutManager(requireActivity(),LinearLayoutManager.VERTICAL,false) //竖向显示adapter = MyYSAdapter1(list, requireActivity())list_view.adapter = adapterif (userVisibleHint) {//判断Fragment是否可见firstLoad = false//将变量置为false}}override fun onDestroyView() {super.onDestroyView()firstLoad = false //视图销毁将变量置为false}override fun setUserVisibleHint(isVisibleToUser: Boolean) {super.setUserVisibleHint(isVisibleToUser)if (firstLoad && isVisibleToUser) { //视图变为可见并且是第一次加载firstLoad = false}}override fun onDestroy() {super.onDestroy()}override fun onClick(v: View?) {when (v?.id) {}}}
4.MyTaskFragment的xml布局
这里我加了分页刷新,自己看是否需要。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"android:layout_width="match_parent"android:layout_height="match_parent"android:background="@color/backColor"><com.scwang.smartrefresh.layout.SmartRefreshLayoutandroid:id="@+id/fbrefresh"android:layout_width="match_parent"android:layout_height="match_parent"android:layout_marginLeft="12dp"android:layout_marginRight="5dp"android:layout_marginBottom="12dp"app:srlEnableLoadMoreWhenContentNotFull="false"><com.hzwl.aidigital.utils.ClassicsHeaderandroid:id="@+id/clssheader"android:layout_width="match_parent"android:layout_height="wrap_content" /><androidx.recyclerview.widget.RecyclerViewandroid:id="@+id/list_view"android:layout_width="match_parent"android:layout_height="match_parent"android:layout_marginTop="10dp"android:layout_marginBottom="10dp"android:overScrollMode="never" /><com.hzwl.aidigital.utils.ClassicsFooterandroid:id="@+id/classicsfooter"android:layout_width="match_parent"android:layout_height="wrap_content" /></com.scwang.smartrefresh.layout.SmartRefreshLayout></LinearLayout>
5.Adapter代码
public class MyYSAdapter1 extends RecyclerView.Adapter<MyYSAdapter1.ViewHolder> {private List<String> list;private Context context;public MyYSAdapter1(List<String> list, Context context) {this.list = list;this.context = context;}/*** 加载更多** @param mPageList*/public void setData(List<String> mPageList) {try {if (mPageList != null) {int previousSize = 0;try {previousSize = list.size();} catch (Exception e) {previousSize = 0;}int sizez = previousSize + 2;list.addAll(mPageList);notifyItemRangeInserted(sizez, mPageList.size());}} catch (Exception e) {e.printStackTrace();}}@Overridepublic ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.mytaskfragment_item, parent, false);ViewHolder viewHolder = new ViewHolder(view);return viewHolder;}/*** 类似GetView** @param holder* @param position*/@Overridepublic void onBindViewHolder(final ViewHolder holder, @SuppressLint("RecyclerView") final int position) {holder.text_name.setText(list.get(position));}//添加元素,需要告诉UI线程布局的变动public void update() {notifyDataSetChanged();}/*** 长度** @return*/@Overridepublic int getItemCount() {return list.size();}/*** 初始化组件*/class ViewHolder extends RecyclerView.ViewHolder {TextView text_name;public ViewHolder(final View itemView) {super(itemView);text_name = itemView.findViewById(R.id.text_name);}}
}
6.item布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="wrap_content"android:background="@color/backColor"android:orientation="vertical"><RelativeLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:layout_marginBottom="16dp"android:layout_marginRight="5dp"android:background="@drawable/bzhs_fff_10"><RelativeLayoutandroid:id="@+id/relative_top"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_marginTop="15dp"><ImageViewandroid:id="@+id/iamg_tp"android:layout_width="56dp"android:layout_height="56dp"android:layout_centerVertical="true"android:layout_marginLeft="15dp"android:src="@mipmap/ico_hometb" /><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:layout_centerVertical="true"android:layout_marginLeft="11dp"android:layout_marginRight="11dp"android:layout_toRightOf="@+id/iamg_tp"android:orientation="vertical"><TextViewandroid:id="@+id/text_name"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="任务名称任务名..."android:textColor="#061C1A"android:textSize="16dp"android:textStyle="bold" /><LinearLayoutandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginTop="6dp"android:gravity="center_vertical"android:orientation="horizontal"><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="审核编号:"android:textColor="#66061C1A"android:textSize="12dp" /><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="23435"android:textColor="#232323"android:textSize="12dp" /><ImageViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginLeft="5dp"android:src="@mipmap/ico_fzal" /></LinearLayout></LinearLayout><LinearLayoutandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignParentRight="true"android:layout_centerVertical="true"android:layout_marginRight="20dp"android:gravity="right"android:orientation="vertical"><LinearLayoutandroid:id="@+id/linear_yb"android:layout_width="wrap_content"android:layout_height="wrap_content"android:orientation="horizontal"><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="+"android:textColor="#FA5151"android:textSize="14dp" /><TextViewandroid:id="@+id/text_num"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="20"android:textColor="#FA5151"android:textSize="24dp"android:textStyle="bold" /><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="元"android:textColor="#FA5151"android:textSize="14dp" /></LinearLayout><LinearLayoutandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:gravity="center_vertical"android:orientation="horizontal"><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="提交限时:"android:textColor="#66061c1a"android:textSize="12dp" /><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="00:59:59"android:textColor="#02C7AB"android:textSize="12dp" /></LinearLayout></LinearLayout></RelativeLayout><RelativeLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:layout_below="@+id/relative_top"android:layout_marginLeft="15dp"android:layout_marginBottom="15dp"android:layout_marginRight="10dp"><LinearLayoutandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_centerVertical="true"android:gravity="center_vertical"android:orientation="horizontal"><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="接单时间:"android:textColor="#66061c1a"android:textSize="12dp" /><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="2025-05-08 15:01:08"android:textColor="#232323"android:textSize="12dp" /></LinearLayout><LinearLayoutandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignParentRight="true"android:layout_centerVertical="true"android:orientation="horizontal"><TextViewandroid:layout_width="wrap_content"android:layout_height="match_parent"android:layout_marginRight="5dp"android:background="@drawable/bzhs_red_20"android:gravity="center"android:paddingLeft="15dp"android:paddingTop="5dp"android:paddingRight="15dp"android:paddingBottom="5dp"android:text="放弃任务"android:textColor="#ffffff"android:textSize="12dp" /><TextViewandroid:layout_width="wrap_content"android:layout_height="match_parent"android:background="@drawable/bzhs_lvse_20"android:gravity="center"android:paddingLeft="15dp"android:paddingTop="5dp"android:paddingRight="15dp"android:paddingBottom="5dp"android:text="提交任务"android:textColor="#ffffff"android:textSize="12dp" /></LinearLayout></RelativeLayout><ImageViewandroid:id="@+id/iamg_bq"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignParentRight="true"android:src="@mipmap/ico_tuijian" /></RelativeLayout></LinearLayout>
总结
总之来说TabLayout+ViewPager没有什么技术难点,需要注意的是TabLayout的item是否铺满屏幕需要xml控制或者代码动态控制,代码都附上了。