1. 程式人生 > >動態新增未知個View,並動態設定點選事件

動態新增未知個View,並動態設定點選事件

先看看效果這裡寫圖片描述

有時候,你不知道需求裡面有幾個View,要根據後臺傳的個數來動態新增

擼程式碼

因為是可以橫向滑動的,所有我用一個HorizontalScrollView包裹一個LinearLayout,在LinearLayout裡面動態add需要的View

佈局檔案

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:background="@color/colorPrimary" android:orientation="vertical" tools:context="duanlian.dynamicaddviewdemo.MainActivity">
<HorizontalScrollView android:layout_width="match_parent" android:scrollbars
="none" android:layout_height="wrap_content">
<LinearLayout android:id="@+id/linear" android:layout_width="match_parent" android:orientation="horizontal" android:layout_height="wrap_content"/> </HorizontalScrollView> <ImageView android:layout_width
="match_parent" android:background="@mipmap/ic_launcher" android:layout_height="match_parent" />
</LinearLayout>

然後就是建立你要動態新增的View,如果是單一的一個控制元件,就不用在去建立一個xml檔案,直接new 出來就行了,我寫的demo裡面有2個控制元件,所有建立一個xml檔案,裡面是你要add的單個view

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"

    android:paddingTop="15dp">

    <ImageView
        android:id="@+id/iv_logo"
        android:layout_width="54dp"
        android:layout_height="54dp"
        android:layout_gravity="center_horizontal"
        android:layout_marginLeft="17dp"
        android:layout_marginRight="17dp"
        android:scaleType="centerCrop" />

    <TextView
        android:id="@+id/tv_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="8dp"
        android:text=""
        android:textColor="#ffff"
        android:textSize="14sp" />
</LinearLayout>

然後就是程式碼裡面操作了

首先find容器,建立兩個集合,一個是裝圖片,一個是裝標題的,在實際開發中這兩個集合裡面的資料肯定是在伺服器上面請求過來的,我這裡是模擬請求的資料

 private void initView() {
        //要新增view的容器
        mLinear = (LinearLayout) findViewById(R.id.linear);
        ivList = new ArrayList<>();
        titleList = new ArrayList<>();

    }

    /**
     * 處理資料,可以是伺服器請求過來的,也可以是本地的
     */
    private void initData() {
        for (int i = 0; i < iv.length; i++) {
            ivList.add(iv[i]);
            titleList.add("第" + i + "個");
        }
        //資料拿到之後去根據資料去動態新增View
        addView();
    }

這是成員變數

private LinearLayout mLinear;
    private List<String> titleList;//放置標題的集合
    private List<Integer> ivList;//放logo的集合
    private int[] iv = {R.drawable.bat,R.drawable.bear,R.drawable.bee,R.drawable.butterfly,R.drawable.cat,R.drawable.deer,
    R.drawable.dolphin,R.drawable.eagle,R.drawable.horse,R.drawable.jellyfish,R.drawable.owl,R.drawable.peacock,
    R.drawable.pig,R.drawable.rat,R.drawable.snake,R.drawable.squirrel};

接下來是動態新增的具體邏輯.註釋很明白

 /**
     * 動態新增的具體實現
     */
    private void addView() {
        //ivList集合有幾個元素就新增幾個
        for (int i = 0; i < ivList.size(); i++) {
            //首先引入要新增的View
            View view = View.inflate(this, R.layout.item_channel, null);
            //找到裡面需要動態改變的控制元件
            ImageView ivLogo = (ImageView) view.findViewById(R.id.iv_logo);
            TextView tvTitle = (TextView) view.findViewById(R.id.tv_title);
            //給控制元件賦值
            ivLogo.setImageResource(ivList.get(i));
            tvTitle.setText(titleList.get(i));
            /*
            動態給每個View設定margin,也可以在xml裡面設定,xml裡面設定後每個view之間的間距都是一樣的
            動態設定可以給每個view之間的間距設定的不一樣 params.setMargins(int left, int top, int right, int bottom);
             */
//            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams
//                    (LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT);
//            view.setLayoutParams(params);
//            params.setMargins(24,0,24,0);
//            view.setTag(i);
            //設定每個View的點選事件
            final int finalI = i;//由於OnClick裡面拿不到i,所以需要重新賦值給一個final物件
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Toast.makeText(MainActivity.this, "點選了"+titleList.get(finalI), Toast.LENGTH_SHORT).show();
                }
            });
            //把所有動態建立的view都新增到容器裡面
            mLinear.addView(view);
        }

    }

還有不明白可以下載demo看看,點選下載