1,第一步 创建一个Class 继承LinearLayout
public class MyView extends LinearLayout {
private DisplayMetrics metrics;
private int srceenWidth=0;
private int srceenHeight=0;
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
metrics = context.getResources().getDisplayMetrics();
srceenWidth=metrics.widthPixels;
srceenHeight=metrics.heightPixels;
setOrientation(VERTICAL);
}
public void setData(String[] data)
{
LinearLayout linearLayout=getLin();
for(int i=0;i<data.length;i++)
{
String tmp=data[i];
int numWidth=0;
int childCount = linearLayout.getChildCount();
for(int j=0;j<childCount;j++)
{
TextView tv = (TextView) linearLayout.getChildAt(j);
LayoutParams params = (LayoutParams) tv.getLayoutParams();
int leftM= params.leftMargin;
tv.measure(getMeasuredWidth(),getMeasuredHeight());
numWidth+=tv.getMeasuredWidth()+leftM+tv.getPaddingLeft()+tv.getPaddingRight();
}
TextView textdata=setText();
LayoutParams params1=new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
params1.leftMargin=10;
params1.topMargin=5;
textdata.setLayoutParams(params1);
textdata.setText(tmp);
textdata.measure(getMeasuredWidth(),getMeasuredHeight());
int textdataWidth=textdata.getMeasuredWidth()+textdata.getPaddingRight()+textdata.getPaddingLeft();
if(srceenWidth>=numWidth+textdataWidth)
{
linearLayout.addView(textdata);
}
else {
linearLayout=getLin();
linearLayout.addView(textdata);
}
}
}
public LinearLayout getLin(){
LinearLayout linearLayout=new LinearLayout(getContext());
LayoutParams params=new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT);
linearLayout.setLayoutParams(params);
this.addView(linearLayout);
return linearLayout;
}
public TextView setText(){
TextView textView=new TextView(getContext());
textView.setTextSize(20);
textView.setTextColor(Color.BLACK);
textView.setPadding(10,10,10,10);
textView.setBackgroundResource(R.drawable.myview_style);
return textView;
}
}
第二步,写avtivity_main.xml
<com.example.moni2.MyView
android:id="@+id/MyView"
android:layout_width="match_parent"
android:layout_height="match_parent"></com.example.moni2.MyView>
第三步,在MainActivity中
public class MainActivity extends AppCompatActivity {
private String[] data = {"流感", "咳嗽", "过敏", "发烧", "感冒", "湿疹", "便秘", "痔疮", "协和", "鼻炎", "失眠", "痛风", "上火", "脚气", "抑郁症", "性欲", "乳腺增生", "头晕", "腰痛"};
private MyView myView;
private MyHeader_View myHeader_view;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myView = findViewById(R.id.MyView);
myHeader_view = findViewById(R.id.MyHeader_View);
myView.setData(data);
}
}