我们在编程的时候,除了可以利用布局中的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){
}