在底部添加几个View控件

运行效果:


image.png

在底部添加几个view控件
TabBarView

public class TabBarView extends ViewGroup {


    //保存所有标签的模型数据
    private ArrayList 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) {
        //每个tab的尺寸
        float density = getResources().getDisplayMetrics().density;
        int width = (int) (50*density);
        //计算间距
        int padding = (getWidth()-width*items.size())/(items.size()+1);
        for (int j= 0; j < items.size(); j++) {
            //创建一个标签视图
            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);
        }
    }
    //提供一个内部类
    //用来管理数据模型
    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 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(){
        //获取对象
        TabBarView tabBar = findViewById(R.id.tab_bar);
        //配置显示的内容
        ArrayList items = new ArrayList<>();
        //创建标签的对象
        TabBarView.TabModel star = new TabBarView.TabModel(R.drawable.activity1,R.drawable.activity2,"活动");
        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



    

    



你可能感兴趣的:(在底部添加几个View控件)