Android:以编程方式在RelativeLayout中添加textViews

Mil*_*loš 2 android textview android-layout

我有一个RelativeLayout,我想插入一些textViews.

这是代码:

 <RelativeLayout
    android:id="@+id/JournalSearchListView"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:minHeight="30dp"
    android:layout_below="@+id/JournalsSearchTextView"
    android:orientation="vertical" 
    android:cacheColorHint="#00000000">

    <ProgressBar
        android:id="@+id/JournalSearchProgressBar"
        style="?android:attr/progressBarStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true" />

</RelativeLayout>
Run Code Online (Sandbox Code Playgroud)

以及我如何以编程方式执行此操作:

RelativeLayout journals = (RelativeLayout) findViewById(R.id.JournalSearchListView);
RelativeLayout.LayoutParams params1 = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);  
for (int i=0;i< authorNames.size();i++) {
    TextView tv = new TextView(this);
    tv.setId(i); 
    tv.setText(authorNames.get(i));
    tv.setTextColor(Color.BLACK);
    Integer a = tv.hashCode();
    map.put(a,authorNames.get(i));
    params1.addRule(RelativeLayout.BELOW, tv.getId());
    journals.addView(tv, params1);
    tv.setOnClickListener(new OnClickListener() {
         public void onClick(View v) {
             System.out.println("Clicked "+ map.get(v.hashCode()) );    
         }
    });   
}
Run Code Online (Sandbox Code Playgroud)

但问题是每个textView与其他textView处于相同的位置.

And*_*nik 5

params1.addRule(RelativeLayout.BELOW, tv.getId());

你是设置它低于自己?
如果你想让它们在彼此之下,就这样做:

RelativeLayout journals = (RelativeLayout);
findViewById(R.id.JournalSearchListView);
LinearLayout lL = new LinearLayout(context);
lL.setOrientation(LinearLayout.VERTICAL);

for (int i=0;i< authorNames.size();i++) {
    TextView tv = new TextView(this);
    tv.setId(i); 
    tv.setText(authorNames.get(i));
    tv.setTextColor(Color.BLACK);
    Integer a = tv.hashCode();
    map.put(a,authorNames.get(i));

    if(i!=0){
        params1.addRule(RelativeLayout.BELOW, i-1);
    }

    tv.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            System.out.println("Clicked "+ map.get(v.hashCode()) ); 
        }
    });

    lL.addView(tv);   

}

journals.addview(lL);
Run Code Online (Sandbox Code Playgroud)