对于动态创建控件一直很抵触的我,今天尝试着扫下我的知识盲点,之前一直是用有道云笔记记录,最近比较依赖csdn尝试着记录一下。
需求:1单纯的实现动态创建布局,2动态控制代码创建的View的显示位置,3,实现类似标签的效果。
我要根据接口返回的数据进行多个View的展示,但是有个问题就是这个数据的个数是不确定的,而且要控制布局的位置,之前本人的做法是码布局,创建足够多的VIew后再在代码里面将这些控件放在一个集合中,在获取数据的时候动态的遍历出数据的大小的同时从集合中取出view用来填充数据。
1,动态创建布局+控制位置:
2,标签效果
private LinearLayout rlayout, rlayout2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rlayout = (LinearLayout) findViewById(R.id.rlayout);
rlayout2 = (LinearLayout) findViewById(R.id.rlayout2);
for(int i = 0; i<20; i++){
if(i%2!=0) {
rlayout.addView(GetTextView(MainActivity.this, String.valueOf(i),R.color.colorAccent));
}else{
rlayout2.addView(GetTextView(MainActivity.this, String.valueOf(i),R.color.aa));
}
}
}
//宽 高 左 上 右 下
public TextView GetTextView(Context context, String str,int color){
TextView textView = new TextView(context);
textView.setText(str);
textView.setBackgroundResource(color);
textView.setTextColor(Color.BLACK);//文字颜色
textView.setTextSize(18);//文字大小
textView.setHeight(60);
return textView;
}
}
布局:
<?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="match_parent">
<LinearLayout
android:id="@+id/rlayout"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="vertical">
</LinearLayout>
<LinearLayout
android:id="@+id/rlayout2"
android:layout_toRightOf="@id/rlayout"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent"
android:orientation="vertical">
</LinearLayout>
</LinearLayout>
<LinearLayout xmlns:android=" http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="@+id/rlayout"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="vertical">
</LinearLayout>
<LinearLayout
android:id="@+id/rlayout2"
android:layout_toRightOf="@id/rlayout"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent"
android:orientation="vertical">
</LinearLayout>
</LinearLayout>