[英]Adding TextView dynamically in RelativeLayout
我正在使用以下代碼。 代碼應在一行中顯示值的值,例如,如果values[]
包含{A,B,C,D,E,F}
,則應在relative layout
顯示ABCDEF
。 如果我不使用LayoutParams pramas
那么所有textViews
都在互相補充。 我如何才能使它們彼此相鄰
for (int i = 0 ; i < values.length ; i++)
{
TextView textView = new TextView(this);
textView.setText(values[i].toString());
textView.setTextColor(Color.BLACK);
textView.setClickable(true);
textView.setId(i);
textView.setBackgroundDrawable(d);
textView.setTextSize(24);
LayoutParams param = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
params.setMargins(5, 50, 0, 0);
if (i>0)
params.addRule(RelativeLayout.RIGHT_OF, i);
textView.setLayoutParams(param);
wordsLayout.addView(textView,params);
}
}
問題是,當我使用wordsLayout.addView(textView,params);
什么都沒有顯示
我們的工作代碼...
LinearLayout wordsLayout = new LinearLayout(this);
for (int i = 0 ; i < 5 ; i++)
{
TextView textView = new TextView(this);
textView.setText(String.valueOf(i));
textView.setTextColor(Color.RED);
textView.setClickable(true);
textView.setId(i);
textView.setBackgroundDrawable(d);
textView.setTextSize(24);
LayoutParams param = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
params.setMargins(5, 50, 0, 0);
if (i>0)
params.addRule(RelativeLayout.RIGHT_OF, i);
textView.setLayoutParams(param);
wordsLayout.addView(textView,params);
}
setContentView(wordsLayout);
我建議將每個Textview放在其自己的Viewgroup中,該Viewgroup環繞Textviews內容大小。 按照您希望所有可見textview的方式將所有Viewgroup彼此並排排列。 並將內部textview-elements設為VISIBLE和GONE,但是您需要顯示它們。 我認為這是最不麻煩的方式,它可以確保您的textview順序。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.