我试图以相对布局动态创建文本视图。
问题:如果屏幕上有足够的空间,如果没有足够的空间,如何将它们添加到RIGHT_OF。
void addTravelActivities()
{
RelativeLayout travel_act_layout=(RelativeLayout) findViewById(R.id.rl_for_travelact);
for (int i=0;i<=15;i++)
{
TextView tv=new TextView(this);
tv.setId(i);
tv.setText(traveliconName.get(i));
tv.setBackgroundResource(R.drawable.round_rect_shape);
tv.setCompoundDrawablesWithIntrinsicBounds(R.drawable.plus_profile,0, 0, 0);
tv.setCompoundDrawablePadding(10);
tv.setTextSize(16f);
tv.setTextColor(this.getResources().getColor(R.color.tripoto_orange));
tv.measure(0, 0);
// tv.setBackground(this.getResources().getDrawable(R.drawable.round_rect_shape,null));
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
if(i==0)
{
params.addRule(RelativeLayout.ALIGN_PARENT_TOP);
params.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
params.setMargins(8,0, 8, 8);
travel_act_layout.addView(tv,params);
/*tv.addOnLayoutChangeListener(new OnLayoutChangeListener() {
@Override
public void onLayoutChange(View v, int left, int top, int right,
int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
// TODO Auto-generated method stub
int width=right-left;
Toast.makeText(NewProfileSettings.this,width+"", Toast.LENGTH_SHORT).show();
}
});*/
}
else if(getWindowSize(tv.getMeasuredWidth())==true) {
params.addRule(RelativeLayout.RIGHT_OF,i-1);
params.setMargins(8,0, 8, 8);
sum += tv.getMeasuredWidth();
travel_act_layout.addView(tv,params);
// Toast.makeText(this, tv.getMeasuredWidth()+"", Toast.LENGTH_SHORT).show();
}
else if(getWindowSize(tv.getMeasuredWidth())==false)
{
params.addRule(RelativeLayout.BELOW,i-1);
params.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
params.setMargins(8,0,8,8);
travel_act_layout.addView(tv,params);
sum=0;
}
}
}
Boolean getWindowSize(int textViewWidth)
{
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;
int layout_width=width-40-textViewWidth;
if(layout_width>sum)
return true;
else
return false;
}
我可能接近这样做,因为我已经接受了这个
答案 0 :(得分:0)
答案:
是Flow Layout是@Frank N. Stein建议的答案。但是你会发现很多库可以帮助你完成这项任务。如果你想避免使用库,这是我在研究时发现的最简单的方法:
https://nishantvnair.wordpress.com/2010/09/28/flowlayout-in-android/
只需要一个类和一些布局的更改,它就可以正常工作。