[英]How can I add textview dynamically from arraylist?
Is it possible add textView in a relative layout dynamically, taking the information from an arraylist?是否可以在相对布局中动态添加 textView,从数组列表中获取信息? I'll explain.我来解释一下。 For example I have a arralist with five words that I get from a database.例如,我有一个 arralist,其中包含从数据库中获取的五个单词。 I would then create 5 different textView in its layout.然后我会在其布局中创建 5 个不同的 textView。 I can not use a listview because it is the user to choose the poszione of these TextView.我不能使用列表视图,因为它是用户选择这些 TextView 的位置。
This is the code I was working, so I was able to create more TextView, but not from the array list.这是我正在使用的代码,因此我能够创建更多 TextView,但不能从数组列表中创建。 I also need to give different values for the top margin at each TextView!我还需要为每个TextView的上边距赋予不同的值!
RelativeLayout rl = (RelativeLayout) findViewById(R.id.sundayRelativeLayout);
TextView iv;
RelativeLayout.LayoutParams params;
float d = this.getResources().getDisplayMetrics().density;
iv = new TextView(this);
iv.setBackgroundColor(Color.YELLOW);
int marginTopDip = 180; // margin in dips
int marginHeightDips = 60; // margin in dips
int height = (int)(marginHeightDips * d);
int margintop = (int)(marginTopDip * d);
params = new RelativeLayout.LayoutParams(500, height);
params.topMargin = margintop;
rl.addView(iv, params);
iv = new TextView(this);
iv.setBackgroundColor(Color.RED);
params = new RelativeLayout.LayoutParams(30, 40);
params.topMargin = 900;
rl.addView(iv, params);
Create like this像这样创建
ArrayList<Integer> list=new ArrayList<Integer>();
if your list size is 5如果您的列表大小为 5
for(int i=0;i<list.size();i++){
TextView tv=new TextView(this);
tv.setText(""+list.get(i));
}
final int N = 10; // total number of textviews to add
final TextView[] myTextViews = new TextView[N]; // create an empty array;
for (int i = 0; i < N; i++) {
// create a new textview
final TextView rowTextView = new TextView(this);
// set some properties of rowTextView or something
rowTextView.setText("This is row #" + i);
// add the textview to the linearlayout
myLinearLayout.addView(rowTextView);
// save a reference to the textview for later
myTextViews[i] = rowTextView;
}
Yeah you can add textview to the relative layout like this.是的,您可以像这样将 textview 添加到相对布局中。
RelativeLayout container = (RelativeLayout) findViewById(R.id.container);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
ArrayList<Integer> list=new ArrayList<Integer>();
for(int i=0;i<list.size();i++){
TextView textView = new TextView(this);
textView1.setText("A"+i);
textView1.setId(i);
container.addView(textView);
params.addRule(RelativeLayout.BELOW,i);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.