自定义控件
public class SelfView extends RelativeLayout {
private Context mcontext;
private LinearLayout layoutall;
private List<String> datas = new ArrayList<>();
private LinearLayout linearhor;
public SelfView(Context context) {
super(context);
init(context);
}
public SelfView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init(context);
}
public SelfView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context);
}
private void init(Context context) {
this.mcontext = context;
//初始化控件
View view = View.inflate(mcontext, R.layout.layout_slfelayout, null);
//初始化主布局
layoutall = view.findViewById(R.id.layout_all);
this.addView(view);
}
public void setData(List<String> data) {
datas = data;
setList(data);
}
private void setList(List<String> list) {
layoutall.removeAllViews();
//创建第二的布局
linearhor = (LinearLayout) View.inflate(mcontext, R.layout.layout_slfe_h, null);
layoutall.addView(linearhor);
linearhor.removeAllViews();
int len = 0;
for (int i = 0; i < list.size(); i++) {
String data = list.get(i);
len += data.length();
if (len > 22) {
linearhor = (LinearLayout) View.inflate(mcontext, R.layout.layout_slfe_h, null);
layoutall.addView(linearhor);
len = 0;
}
View viewtxt = View.inflate(mcontext, R.layout.layout_self_image, null);
TextView txt = viewtxt.findViewById(R.id.show_text);
txt.setText(data);
Log.d("Tag", data + ">>>>");
linearhor.addView(viewtxt);
LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) viewtxt.getLayoutParams();
layoutParams.weight = 1;
layoutParams.topMargin = 10;
layoutParams.leftMargin = 10;
layoutParams.rightMargin = 10;
viewtxt.setLayoutParams(layoutParams);
}
}
}
布局1:
<?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"
android:orientation="horizontal">
</LinearLayout>
布局2:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="@+id/layout_all"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"></LinearLayout>
</LinearLayout>
布局3:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1">
<TextView
android:id="@+id/show_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:background="@drawable/yuan"
android:text="@string/app_name"
android:textSize="20sp" />
</RelativeLayout>