首先在activity的布局文件中添加一个LinearLayout装需要动态添加的view:
activity_main.xml
<LinearLayout
android:id="@+id/ll_bottom"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="50dp"
android:layout_gravity="bottom"
android:orientation="horizontal"
android:background="#fff"
app:layout_constraintBottom_toBottomOf="parent"></LinearLayout>
然后在activity中动态获取:
private ArrayList<View> bottomView = new ArrayList<>(); //保存动态添加的底部按钮
LinearLayout ll_bottom; //装载view 的父布局
private ArrayList<String> data = new ArrayList<>(); //假数据
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ll_bottom = findViewById(R.id.ll_bottom);
initData();
getBoomView();
}
private void getBoomView() {
bottomView.clear(); //先清除 再添加
ll_bottom.removeAllViews();
for(int i = 0;i<data.size();i++){
final LinearLayout ll= (LinearLayout) LayoutInflater.from(MainActivity.this).inflate(R.layout.item_bottom_view,null); //自定义的布局
ll.setLayoutParams(new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, 1));//此处设置权重 三个参数:宽,高,权重
// final ImageView ivLogo=(ImageView)ll.findViewById(R.id.iv_bottom_logo);
// Glide.with(MainActivity.this).load(data.source).into(ivLogo); //如果有图片资源就加载
final TextView tvBottom=(TextView)ll.findViewById(R.id.tv_bottom);
tvBottom.setText(data.get(i));
bottomView.add(ll);
ll_bottom.addView(ll);
}
for(int a = 0 ; a<data.size();a++) {
final int finalI = a;
bottomView.get(a).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this,"点击了 "+ data.get(finalI),Toast.LENGTH_SHORT).show();
}
});
}
}
private void initData() {
data.clear();
data.add("首页");
data.add("商城");
data.add("发现");
data.add("我的");
}
item_bottom_view.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="0dp"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
android:padding="5dp"
>
<ImageView
android:id="@+id/iv_bottom_logo"
android:layout_width="30dp"
android:layout_height="30dp"
android:src="@mipmap/ic_launcher"
/>
<TextView
android:id="@+id/tv_bottom"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="14sp"
android:layout_marginTop="4dp"
/>
</LinearLayout>
效果图:
|