动态添加组件,添加id,获取子控件,移除控件

动态创建关键代码(新添加的view是自己写的xml布局view)

 // 1. 获取自定义的 View
Button button = (Button) LayoutInflater.from(this).inflate(R.layout.custom_layout_btn, linearLayout, false); // linearLayout 是父容器,通过findViewById()来获取
// Button button = new Button(this); // 不使用自定义,使用系统组件可以这样使用 // 其他参数一样设置
button.setText("按钮" ); // 可以设置其他的参数,但是推荐在xml布局里写
 // 2. 设置要添加的组件的参数
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
layoutParams.gravity = Gravity.CENTER_HORIZONTAL;
// 3. 父容器里加入子布局
inearLayout.addView(button, 0, layoutParams); // 在container 的第0个位置放此按钮,layoutParms 是新添加组件的布局参数

设置id的方法,在资源文件里声明

如:
type=“id” 是关键

<item name="custom_btn1" type="id">custom_btn1</item>

为button添加id,动态添加的 id 也只能是唯一的,如果为多个组件添加同一个id,效果就是最后一次添加的id才算 ,并且会出现其他错误

button.setId(R.id.custom_btn1);

获取子控件

 Button button = (Button) linearLayout.getChildAt(0); //获取第一个孩子,linearLayout 是父容器
 //linearLayout.getChildCount(); // 所有孩子个数

移除控件

linearLayout.removeAllViews(); // 移除所有组件包括linearLayout
linearLayout.removeAllViewsInLayout();  // 只移除子控件
linearLayout.removeView();  // 移除具体view ,一般和点击事件一起使用

实例:

功能:

  1. 添加button,为button设置点击事件
  2. 获取 activity_main.xml 的最大布局的第一子孩子,判断 id 是不是 custom_btn1

在这里插入图片描述

资源文件
ids.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <item name="custom_btn1" type="id">custom_btn1</item>
    <item name="custom_btn2" type="id">custom_btn2</item>
    <item name="custom_btn3" type="id">custom_btn3</item>
    <item name="custom_btn4" type="id">custom_btn4</item>
    <item name="custom_btn5" type="id">custom_btn5</item>
</resources>

自定义Button

<?xml version="1.0" encoding="utf-8"?>
<Button xmlns:android="http://schemas.android.com/apk/res/android"
    android:text="按钮"
    android:background="@color/colorPrimary"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
</Button>

主布局
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/container"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/addCustomView"
        android:onClick="click"
        android:text="添加子控件"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <Button
        android:id="@+id/getChildView"
        android:onClick="matchId"
        android:text="获取子控件"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

MainActivity.java

package com.example.tnt.dynamicview;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private int number = 0;
    LinearLayout linearLayout;
    Toast toast;
    private String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        linearLayout = findViewById(R.id.container);

    }


    public void click(View view) {
        switch (view.getId()) {
            case R.id.addCustomView:
                // 1. 获取自定义的 View
                Button button = (Button) LayoutInflater.from(this).inflate(R.layout.custom_layout_btn, linearLayout, false);
                addId(number, button);
                button.setText("按钮" + number++);
                // 2. 设置View 的参数,推荐在xml中设置
                LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                layoutParams.gravity = Gravity.CENTER_HORIZONTAL;
                // 3. 父容器里加入子布局
                linearLayout.addView(button, 0, layoutParams); // 在container 的第0个位置放此按钮
                // 还有其他几个添加布局的重写方法
//                linearLayout.addView(button);
//                linearLayout.addView(button,layoutParams);
//                linearLayout.addView(button, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);

                break;
        }
    }

    private void addId(int number, final Button button) {
        switch (number) {
            case 0:
                button.setId(R.id.custom_btn1);
                break;
            case 1:
                button.setId(R.id.custom_btn2);
                break;
            case 2:
                button.setId(R.id.custom_btn3);
                break;
            case 3:
                button.setId(R.id.custom_btn4);
                break;
            case 4:
                button.setId(R.id.custom_btn5);
                break;
        }

        // 设置 button 的点击事件
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showToast(button, "");
                Log.i(TAG, String.valueOf(button.getId()));
            }
        });
    }

    // 匹配id
    public void matchId(View view) {
        Button button = (Button) linearLayout.getChildAt(0);
//        linearLayout.getChildCount(); // 所有孩子个数

        Toast.makeText(this, "第一个孩子是:" + button.getText(), Toast.LENGTH_SHORT).show();

        if (button.getId() == R.id.custom_btn1) {
            System.out.println("btn 的ID 是:" + button.getId());
            showToast(button, "找到了custom_btn1"); // 找到了
        } else {
            showToast(button, "不是custom_btn1"); // 没找到
        }
    }


    private void showToast(Button button, String mes) {
        if (toast == null) {
            toast = Toast.makeText(this, button.getText() + mes, Toast.LENGTH_SHORT);
        } else {
            toast.setText(button.getText() + mes);
            toast.setDuration(Toast.LENGTH_SHORT);
        }
        toast.show();
    }
}

本人技术有限,如果有更方便的方法,还请告知。

猜你喜欢

转载自blog.csdn.net/qq_38340601/article/details/82932141