Android實現動態添加控件


xml文件:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/activity_student_sign_up"
android:background="@android:color/darker_gray"
tools:context="com.example.myapplication.student_signUp" >

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:scrollbars="none" >

    <LinearLayout
        android:id="@+id/content_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:isScrollContainer="true"
        android:orientation="vertical"
        android:padding="10.0dip" >

        <LinearLayout
            android:id="@+id/ll_one"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="5dip"
            android:background="#FFA2CD5A"
            android:orientation="vertical"
            android:padding="5dip" >

            <EditText
                android:id="@+id/et_content1"
                android:layout_width="match_parent"
                android:layout_height="80dip"
                android:background="#FFFFFFFF"
                android:gravity="left"
                android:inputType="textMultiLine"
                android:paddingLeft="5dip"
                android:textSize="16sp" />

            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="5dip" >

                <ImageButton
                    android:id="@+id/ibn_add1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentRight="true"
                    android:background="@drawable/add" />
                <!--
                                    <ImageButton
                                        android:id="@+id/ibn_del1"
                                        android:layout_width="wrap_content"
                                        android:layout_height="wrap_content"
                                        android:layout_marginRight="10dip"
                                        android:layout_toLeftOf="@id/ibn_add1"
                                        android:background="@drawable/ic_delete" />
                 -->
            </RelativeLayout>
        </LinearLayout>
    </LinearLayout>
</ScrollView>

</RelativeLayout>

java文件

package com.example.myapplication;

import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.InputType;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.util.LinkedList;
import java.util.concurrent.atomic.AtomicInteger;

public class student_signUp extends AppCompatActivity {

    // 外圍的LinearLayout容器
    private LinearLayout llContentView;

    private EditText etContent1;

    // “+”按鈕控件List
    private LinkedList<ImageButton> listIBTNAdd;
    // “+”按鈕ID索引
    private int btnIDIndex = 1000;
    // “-”按鈕控件List
    private LinkedList<ImageButton> listIBTNDel;

    private int iETContentHeight = 0;   // EditText控件高度
    private float fDimRatio = 1.0f; // 尺寸比例(實際尺寸/xml文件里尺寸)

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_student_sign_up);

        initCtrl();


    }

    /**
     * 初始化控件
     */
    private void initCtrl()
    {
        llContentView = (LinearLayout) this.findViewById(R.id.content_view);
        etContent1 = (EditText) this.findViewById(R.id.et_content1);
        listIBTNAdd = new LinkedList<ImageButton>();
        listIBTNDel = new LinkedList<ImageButton>();

        // “+”按鈕(第一個)
        ImageButton ibtnAdd1 = (ImageButton) this.findViewById(R.id.ibn_add1);
        ibtnAdd1.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // 獲取尺寸變化比例
                iETContentHeight = etContent1.getHeight();
                fDimRatio = iETContentHeight / 80;

                addContent(v);
            }
        });

        listIBTNAdd.add(ibtnAdd1);
        listIBTNDel.add(null);  // 第一組隱藏了“-”按鈕,所以為null
    }

    /**
     * 添加一組新控件
     * @param v 事件觸發控件,其實就是觸發添加事件對應的“+”按鈕
     */
    private void addContent(View v) {
        if (v == null) {
            return;
        }

        // 判斷第幾個“+”按鈕觸發了事件
        int iIndex = -1;
        for (int i = 0; i < listIBTNAdd.size(); i++) {
            if (listIBTNAdd.get(i) == v) {
                iIndex = i;
                break;
            }
        }

        if (iIndex >= 0) {
            // 控件實際添加位置為當前觸發位置點下一位
            iIndex += 1;
            Toast.makeText(this,""+iIndex,Toast.LENGTH_LONG).show();
            // 開始添加控件

            // 1.創建外圍LinearLayout控件
            LinearLayout layout = new LinearLayout(student_signUp.this);
            LinearLayout.LayoutParams lLayoutlayoutParams = new LinearLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);
            // 設置margin
            lLayoutlayoutParams.setMargins(0, (int) (fDimRatio * 5), 0, 0);
            layout.setLayoutParams(lLayoutlayoutParams);
            // 設置屬性
            layout.setBackgroundColor(Color.argb(255, 162, 205, 90));   // #FFA2CD5A
            layout.setPadding((int) (fDimRatio * 5), (int) (fDimRatio * 5),
                    (int) (fDimRatio * 5), (int) (fDimRatio * 5));
            layout.setOrientation(LinearLayout.VERTICAL);

            // 2.創建內部EditText控件
            EditText etContent = new EditText(student_signUp.this);
            LinearLayout.LayoutParams etParam = new LinearLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT, iETContentHeight);
            etContent.setLayoutParams(etParam);
            // 設置屬性
            etContent.setBackgroundColor(Color.argb(255, 255, 255, 255));   // #FFFFFFFF
            etContent.setGravity(Gravity.LEFT);
            etContent.setInputType(InputType.TYPE_TEXT_FLAG_MULTI_LINE);
            etContent.setPadding((int) (fDimRatio * 5), 0, 0, 0);
            etContent.setTextSize(16);
            etContent.setId(generateViewId());
            System.out.println("etContent"+etContent.getId());
            // 將EditText放到LinearLayout里
            //etContent.getId();
            layout.addView(etContent);

            // 2.創建內部EditText控件
            EditText etContent1 = new EditText(student_signUp.this);
            LinearLayout.LayoutParams etParam1 = new LinearLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT, iETContentHeight);
            etContent1.setLayoutParams(etParam1);
            // 設置屬性
            etContent1.setBackgroundColor(Color.argb(255, 0, 255, 0));   // #FFFFFFFF
            etContent1.setGravity(Gravity.LEFT);
            etContent1.setInputType(InputType.TYPE_TEXT_FLAG_MULTI_LINE);
            etContent1.setPadding((int) (fDimRatio * 5), 0, 0, 0);
            etContent1.setTextSize(16);
            // 將EditText放到LinearLayout里
            etContent1.setId(generateViewId());
            System.out.println("etContent1"+etContent.getId());
            Toast.makeText(v.getContext(),"text-id;"+etContent1.getId(),Toast.LENGTH_LONG).show();;
            layout.addView(etContent1);

            // 3.創建“+”和“-”按鈕外圍控件RelativeLayout
            RelativeLayout rlBtn = new RelativeLayout(student_signUp.this);
            RelativeLayout.LayoutParams rlParam = new RelativeLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);
//          rlParam.setMargins(0, (int) (fDimRatio * 5), 0, 0);
            rlBtn.setPadding(0, (int) (fDimRatio * 5), 0, 0);
            rlBtn.setLayoutParams(rlParam);

            // 4.創建“+”按鈕
            ImageButton btnAdd = new ImageButton(student_signUp.this);
            RelativeLayout.LayoutParams btnAddParam = new RelativeLayout.LayoutParams(
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);
            // 靠右放置
            btnAddParam.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
            btnAdd.setLayoutParams(btnAddParam);
            // 設置屬性
            btnAdd.setBackgroundResource(R.drawable.add);

            // 設置點擊操作
            btnAdd.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    addContent(v);
                }
            });
            // 將“+”按鈕放到RelativeLayout里
            rlBtn.addView(btnAdd);
            listIBTNAdd.add(iIndex, btnAdd);

            // 5.創建“-”按鈕
            ImageButton btnDelete = new ImageButton(student_signUp.this);
            btnDelete.setBackgroundResource(R.drawable.delete);
            RelativeLayout.LayoutParams btnDeleteAddParam = new RelativeLayout.LayoutParams(
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);
            btnDeleteAddParam.setMargins(0, 0, (int) (fDimRatio * 5), 0);
            // “-”按鈕放在“+”按鈕左側
            btnDeleteAddParam.addRule(RelativeLayout.LEFT_OF, btnIDIndex);
            btnDelete.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    Toast.makeText(v.getContext(),"該插件id;"+v.getId(),Toast.LENGTH_LONG).show();
                    deleteContent(v);
                }
            });
            // 將“-”按鈕放到RelativeLayout里
            rlBtn.addView(btnDelete, btnDeleteAddParam);
            listIBTNDel.add(iIndex, btnDelete);

            // 6.將RelativeLayout放到LinearLayout里
            layout.addView(rlBtn);

            // 7.將layout同它內部的所有控件加到最外圍的llContentView容器里
            llContentView.addView(layout, iIndex);

            btnIDIndex++;
        }
    }

    /**
     * 刪除一組控件
     * @param v 事件觸發控件,其實就是觸發刪除事件對應的“-”按鈕
     */
    private void deleteContent(View v) {
        if (v == null) {
            return;
        }

        // 判斷第幾個“-”按鈕觸發了事件
        int iIndex = -1;
        for (int i = 0; i < listIBTNDel.size(); i++) {
            if (listIBTNDel.get(i) == v) {
                iIndex = i;
                break;
            }
        }
        if (iIndex >= 0) {
            listIBTNAdd.remove(iIndex);
            listIBTNDel.remove(iIndex);

            // 從外圍llContentView容器里刪除第iIndex控件
            llContentView.removeViewAt(iIndex);
        }
    }

    /*@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }  */

    //為每一個控件設置一個id
    private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);
    public static int generateViewId() {
        for (; ; ) {
            final int result = sNextGeneratedId.get();
            // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
            int newValue = result + 1;
            if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
            if (sNextGeneratedId.compareAndSet(result, newValue)) {
                return result;
            }
        }
    }

    public static int generateViewId(int a) {

            final int result = a;
            return result;
    }


}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM