運(yùn)行效果:
在底部添加幾個(gè)view控件
TabBarView
public class TabBarView extends ViewGroup {
//保存所有標(biāo)簽的模型數(shù)據(jù)
private ArrayList<TabModel> items;
public TabBarView(Context context) {
super(context);
}
public TabBarView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onLayout(boolean b, int i, int i1, int i2, int i3) {
//每個(gè)tab的尺寸
float density = getResources().getDisplayMetrics().density;
int width = (int) (50*density);
//計(jì)算間距
int padding = (getWidth()-width*items.size())/(items.size()+1);
for (int j= 0; j < items.size(); j++) {
//創(chuàng)建一個(gè)標(biāo)簽視圖
View v = new View(getContext());
v.setBackgroundColor(Color.WHITE);
//具體布局
//距離左邊的間距
int left = (j+1)*padding+j*width;
int top = (int) (5*density);
int right = left +width;
int bottom = (int) (getHeight()-5*density);
v.layout(left,top,right,bottom);
//添加
addView(v);
}
}
//提供一個(gè)內(nèi)部類
//用來管理數(shù)據(jù)模型
public static class TabModel{
public int icon_normal;
public int icon_select;
public String title;
public TabModel(int icon_normal, int icon_select, String title) {
this.icon_normal = icon_normal;
this.icon_select = icon_select;
this.title = title;
}
}
public void setItems(ArrayList<TabModel> items) {
this.items = items;
}
}
主界面
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
public void init(){
//獲取對(duì)象
TabBarView tabBar = findViewById(R.id.tab_bar);
//配置顯示的內(nèi)容
ArrayList<TabBarView.TabModel> items = new ArrayList<>();
//創(chuàng)建標(biāo)簽的對(duì)象
TabBarView.TabModel star = new TabBarView.TabModel(R.drawable.activity1,R.drawable.activity2,"活動(dòng)");
TabBarView.TabModel friend = new TabBarView.TabModel(R.drawable.people2,R.drawable.people1,"好友");
items.add(star);
items.add(friend);
items.add(star);
items.add(friend);
tabBar.setItems(items);
}
}
xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:layout_height="match_parent"
tools:context=".MainActivity"
android:id="@+id/root">
<swu.zht.a11_30test.TabBarView
android:id="@+id/tab_bar"
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_alignParentBottom="true"
android:background="@color/colorAccent"
>
</swu.zht.a11_30test.TabBarView>
</RelativeLayout>