动态添加View

效果图:

动态添加View_第1张图片

 

Kotlin代码:

//1.寻找到可以添加控件的一些根布局:如LinearLayout
        val linearLayout = findViewById(R.id.line_view) as LinearLayout

        val lv0_params = LinearLayout.LayoutParams(dp2px(this, 200f), dp2px(this, 50f))

        for (index in 1..10){
            //根据业务需求,加载单个UI的布局
            val convertView = View.inflate(this, R.layout.list_item, null)
            val tv_one =  convertView.findViewById(R.id.wenben_tv_one)
            val item_line =  convertView.findViewById(R.id.item_line)
            val lin_item =  convertView.findViewById(R.id.lin_item)
            tv_one.text = "更改的文本:"+index
            if (index == 10){
                item_line.visibility = View.GONE
            }
            linearLayout.addView(convertView, lv0_params)//要添加lv0_params,否则宽高不准
            lin_item.setOnClickListener {
                Toast.makeText(this,"点击文本:"+index,Toast.LENGTH_SHORT).show()
            }
        }

Java代码:

for (final BackDataToRestore restore : mDatas.get(position).getDataList()) {
            View view =LayoutInflater.from(mContext).inflate(R.layout.layout_item, holder.liner_item_manager_add,false);
            TextView item_restore_name = view.findViewById(R.id.item_restore_name);
            TextView item_restore_time = view.findViewById(R.id.item_restore_time);
            TextView item_restore_capacity = view.findViewById(R.id.item_restore_capacity);
            item_restore_name.setText(restore.getDataName());
            item_restore_time.setText(restore.getDataTime());
            item_restore_capacity.setText(restore.getDataCapacity());
            holder.liner_item_manager_add.addView(view);

            if (mOnItemClickListener != null) {
                view.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        mOnItemClickListener.onItemClick(view, position,restore);
                    }
                });
            }

        }

 

你可能感兴趣的:(拒绝重复造轮子)