Android动态生成TextView并设置Margin

我们在编程的时候,除了可以利用布局中的TextView来显示数据,同样我们也可以利用对象来动态创建TextView,并展示数据。

1、创建TextView对象

2、添加数据和属性值

3、把TextView设置为布局的子节点

     LinearLayout ll = (LinearLayout) findViewById(R.id.lay);
        //把数据显示至屏幕
       String[] descriptionSp = description.split("、");
            for (int j = 0;j < descriptionSp.length;j++) {
        	//1.集合中每有一条元素,就new一个textView
			TextView tv = new TextView(this);
			//2.把信息设置为文本框的内容
			tv.setText(p.toString());
			tv.setTextSize(20);
			//3.把textView设置为线性布局的子节点
			ll.addView(tv);
	}

这样写的TextView 是连接在一起,所以可以设置margin

1、如果这个控件实在XML中定义的

LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) textview.getLayoutParams();
lp.leftMargin = 0;
textview.setLayoutParams(lp);

2、如果这个控件是我们new出来的,就会会发现用上面的方法就会有空指针报错了。然后我们用另一种方法

LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(10,10,10,10);//4个参数按顺序分别是左上右下
textview.setLayoutParams(layoutParams);

综合在一起

 String description = info.getDescription();//数据源
        try {
            String[] descriptionSp = description.split("、");
            hoder.descriptionLl.removeAllViews();//添加之前先remove,不然会重复添加
            for (int j = 0;j < descriptionSp.length;j++) {
                //1.集合中每有一条元素,就new一个textView
                TextView tv = new TextView(mContext);
                //2.把信息设置为文本框的内容
                tv.setText(descriptionSp[j].toString());
                tv.setTextSize(12);
                tv.setTextColor(mContext.getResources().getColor(R.color.src_text_c2));
                tv.setBackgroundColor(mContext.getResources().getColor(R.color.src_c44));
                tv.setPadding(5,5,5,5);
                LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                layoutParams.setMargins(2,0,2,0);//4个参数按顺序分别是左上右下
                tv.setLayoutParams(layoutParams);
                //3.把textView设置为线性布局的子节点
                hoder.descriptionLl.addView(tv);
            }
        }catch (Exception e){

        }
  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值