布局显示:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!--
对tabLayout进行设置
app:tabMode="scrollable" 可以滚动
app:tabGravity="center"居中显示
app:tabIndicatorColor="#00ff00"设置指示器的颜色(下面的横线)
app:tabTextColor="#000000"设置没选中的字体颜色
app:tabSelectedTextColor="#00ff00"选中时的字体颜色
-->
<android.support.design.widget.TabLayout
android:id="@+id/tab_layout"
app:tabMode="scrollable"
app:tabGravity="center"
app:tabIndicatorColor="#00ff00"
app:tabTextColor="#000000"
app:tabSelectedTextColor="#00ff00"
android:layout_width="match_parent"
android:layout_height="60dp">
</android.support.design.widget.TabLayout>
<FrameLayout
android:id="@+id/frame_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
</LinearLayout>
代码:
package com.example.a12_tablayout_01;
import android.support.design.widget.TabLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;
/**
* tablayout单独使用,,,没有结合viewPager
*/
public class MainActivity extends AppCompatActivity {
private TabLayout tabLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tabLayout = (TabLayout) findViewById(R.id.tab_layout);
//添加标题
for (int i=0;i<20;i++){
tabLayout.addTab(tabLayout.newTab().setText("TAB"+i));
}
//监听事件
//tabLayout.setOnTabSelectedListener();//废弃但是能用,使用方法和addOnTabSelectedListener一样
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
//选中的时候
@Override
public void onTabSelected(TabLayout.Tab tab) {
String text = tab.getText().toString();
if (text.equals("头条")){
}
//可以使用fragemnt替换frameLayout
Toast.makeText(MainActivity.this,"替换了:"+tab.getText(),Toast.LENGTH_SHORT).show();
}
//未选中的时候
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
//再次选中的时候
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
}