1.创建类继承LinearLayout 方法
// 得到整个屏幕的宽度
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
pwidth = metrics.widthPixels;
setOrientation(VERTICAL);
public LinearLayout getlinearLayout() {
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 getTextView() {
TextView textView =new TextView(getContext());
textView.setTextSize(20);
textView.setBackgroundResource(R.drawable.text);
textView.setTextColor(Color.parseColor("#FF3D7EBF"));
textView.setPadding(10,10,10,10);
return textView;
}
public void getData(List data) {
LinearLayout linearLayout = getlinearLayout();
for (int i =0; i < data.size(); i++) {
String temp = data.get(i);
int linWidth =0;
int count = linearLayout.getChildCount();
for (int j =0; j < count; j++) {
TextView textView = (TextView) linearLayout.getChildAt(j);
LayoutParams params = (LayoutParams) textView.getLayoutParams();
int leftMargin = params.leftMargin;
textView.measure(getMeasuredWidth(), getMeasuredHeight());
linWidth += textView.getMeasuredWidth() + leftMargin + textView.getPaddingLeft();
}
final TextView textView = getTextView();
LayoutParams params = (LayoutParams)new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
params.leftMargin =10;
params.topMargin =2;
textView.setLayoutParams(params);
textView.setText(temp);
textView.measure(getMeasuredWidth(),getMeasuredHeight());
int textWidth = textView.getMeasuredWidth() + textView.getPaddingLeft() + textView.getPaddingRight();
textView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getContext(),textView.getText().toString()+"", Toast.LENGTH_SHORT).show();
}
});
if(pwidth>=textWidth+linWidth){
linearLayout.addView(textView);
}else{
linearLayout = getlinearLayout();
linearLayout.addView(textView);
}
}
}
网友评论