Android Fragment RelativeLayout 动态生成TextView 事件

Android Fragment RelativeLayout 动态生成TextView 事件

package cn.mf.cts;

import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

/**
 * CopyRright (c)2018-2028: chanpinxue.cn
 * Project: cts
 * Module Name: Mine
 * Comments: 我的
 * JDK version used: JDK1.8
 * Author: jzh
 * Create Date: 2018-09-17
 * Modified By: jzh
 * Modified Date: 2018-09-17
 * Why & What is modified:
 * Version: <1.0>
 */
public class MineFragment extends Fragment {

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_mine, null,false);


        // TextView宽度和高度
        int width = 200;
        int height = 120;

        // 自定义layout组件
        RelativeLayout layout = new RelativeLayout(getContext());
        FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.FILL_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT);

        // 创建16个TextView,每行放置4个TextView
        TextView arrTV[] = new TextView[16];
        int j = -1;
        for (int i = 0; i <= 15; i++) {
            arrTV[i] = new Button(getContext());
            arrTV[i].setId(100 + i);
            arrTV[i].setText("测试" + i);
            arrTV[i].setTextColor(Color.RED);
            arrTV[i].setTextSize(12);
            RelativeLayout.LayoutParams btParams = new RelativeLayout.LayoutParams(width, height);
            if (i % 4 == 0) {
                j++;
            }
            btParams.leftMargin = 10 + (width + 10) * (i % 4); // 横坐标定位
            btParams.topMargin = 20 + height * j; // 纵坐标定位
            layout.addView(arrTV[i], btParams); // 加入layout组件
        }

        // 加入view
        //this.setContentView(layout);
        getActivity().addContentView(layout, layoutParams);

        // 批量设置监听
        for (int k = 0; k <= arrTV.length - 1; k++) {
            arrTV[k].setTag(k); // 设置标记

            arrTV[k].setOnClickListener(new Button.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int i = (Integer) v.getTag();
                    System.out.println("测试" + String.valueOf(i));
                }
            });
        }

        return view;
    }
}

 

发表回复

您的电子邮箱地址不会被公开。