<android.support.design.widget.TabLayout android:id="@+id/tabLayout" android:layout_width="match_parent" /> //初始化 tabLayout.addTab(tabLayout.newTab().setText(tab)); //监听事件 tabLayout.addOnTabSelectedListener(this);
Activity布局
<?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" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:orientation="vertical" android:layout_height="match_parent" tools:context=".MainActivity"> <android.support.design.widget.TabLayout android:id="@+id/tab_id" app:tabSelectedTextColor="#E5AF35" app:tabTextColor="#969696" app:tabIndicatorColor="#E5AF35" app:tabIndicatorHeight="5dp" app:tabMode="scrollable" android:layout_weight="1" android:layout_width="match_parent" android:layout_height="0dp"> </android.support.design.widget.TabLayout>
MainActivity代码
public class MainActivity extends AppCompatActivity { private TabLayout tabId; private ViewPager vpId; private List<Fragment> list = new ArrayList<>(); private List<String> titles = new ArrayList<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); supportRequestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_main); tabId = findViewById(R.id.tab_id); vpId = findViewById(R.id.vp_id); list.add(new OneFragment()); list.add(new TwoFragment()); list.add(new OneFragment()); list.add(new TwoFragment()); titles.add("视频"); titles.add("新闻"); titles.add("图片"); titles.add("留言");
Banner的应用
导入外部依赖
implementation 'com.github.bumptech.glide:glide:3.7.0' implementation 'com.youth.banner:banner:1.4.9'
编写布局
<com.youth.banner.Banner android:id="@+id/banner" android:layout_width="match_parent" android:layout_height="200dp"> </com.youth.banner.Banner>
创建Banner对象,设置属性
public class MainActivity extends AppCompatActivity implements OnBannerListener { private Banner banner; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); banner = findViewById(R.id.banner);//一定要布局文件之后获取ID List<Integer> imageList = new ArrayList<>(); int[] imageIDs = new int[]{R.drawable.gao, R.drawable.yun, R.drawable.img1}; List<String> nameList = new ArrayList<>(); String[] names = new String[]{"1", "2", "3", "4"}; imageList.add(imageIDs[0]); imageList.add(imageIDs[1]); imageList.add(imageIDs[2]); nameList.add(names[0]); nameList.add(names[1]); nameList.add(names[2]);