1

Я пытаюсь добавить правило НИЖЕ, чтобы разместить TextView под другим, но я не могу сделать это программно. У меня есть XML, как это: Layout Params ниже не работает программно

 <android.support.v7.widget.CardView 
      xmlns:card_view="http://schemas.android.com/apk/res-auto" 
      android:id="@+id/card_view" 
      android:layout_gravity="center" 
      android:layout_width="match_parent" 
      android:layout_height="200dp" 
      card_view:cardCornerRadius="4dp" 
      card_view:cardBackgroundColor="#00bcd4"> 

      <RelativeLayout 
       android:layout_width="match_parent" 
       android:layout_height="match_parent" 
       android:paddingBottom="@dimen/activity_vertical_margin" 
       android:paddingLeft="@dimen/activity_horizontal_margin" 
       android:paddingRight="@dimen/activity_horizontal_margin" 
       android:paddingTop="@dimen/activity_vertical_margin"> 

       <TextView 
        android:id="@+id/info_text" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:text="Category Name" 
        style="@style/Base.TextAppearance.AppCompat.Title" 
        android:paddingBottom="@dimen/activity_vertical_margin" 
        android:layout_centerHorizontal="true" /> 

       <TextView 
        android:layout_width="match_parent" 
        android:layout_height="match_parent" 
        android:text="Vel voluptatem soluta ipsa. Voluptatem est quod non explicabo aut quisquam quas. Voluptatem aliquam iure voluptas" 
        android:id="@+id/textView" 
        android:paddingBottom="@dimen/activity_vertical_margin" 
        android:layout_below="@+id/info_text" 
        android:layout_above="@+id/button"/> 

       <Button 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:text="Help" 
        android:id="@+id/button" 
        android:layout_alignParentBottom="true" 
        android:layout_alignParentEnd="true" /> 

       <Button 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:text="Play" 
        android:id="@+id/button2" 
        android:layout_alignParentBottom="true" 
        android:layout_alignParentStart="true" /> 

      </RelativeLayout> 
     </android.support.v7.widget.CardView> 

    </LinearLayout> 

И это работает отлично! Я получил именно тот результат, который я хочу: CardView с названием категории, описанием и двумя кнопками.
Итак, я попытался перенести этот XML на Java, потому что у меня есть много категорий для показа. Я сделал так:

LinearLayout linearLayoutCategory = (LinearLayout) findViewById(R.id.linearLayoutCategory); 
    for (int i = 0; i < categories.size(); i++) { 
     Category category = categories.get(i); 
     CardView cardView = new CardView(this); 
     cardView.setCardBackgroundColor(Color.parseColor("#00bcd4")); 
     cardView.setRadius((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4, getResources().getDisplayMetrics())); 
     LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 200, getResources().getDisplayMetrics()), Gravity.CENTER); 
     layoutParams.setMargins(0, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 16, getResources().getDisplayMetrics()), 0, 0); 
     cardView.setLayoutParams(layoutParams); 

     RelativeLayout relativeLayout = new RelativeLayout(this); 
     RelativeLayout.LayoutParams layoutParams1 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT); 
     relativeLayout.setLayoutParams(layoutParams1); 

     TextView textView = new TextView(this); 
     RelativeLayout.LayoutParams layoutParams2 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); 
     layoutParams2.addRule(RelativeLayout.CENTER_HORIZONTAL); 
     textView.setLayoutParams(layoutParams2); 
     textView.setText(category.getName()); 
     textView.setTextAppearance(this, android.R.style.TextAppearance_Large); 
     textView.setId(i); 
     relativeLayout.addView(textView); 

     TextView textView1 = new TextView(this); 
     RelativeLayout.LayoutParams layoutParams3 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT); 
     layoutParams3.addRule(RelativeLayout.BELOW, textView.getId()); 
     textView1.setLayoutParams(layoutParams3); 
     textView1.setText(category.getDescription()); 
     relativeLayout.addView(textView1); 

     Button button = new Button(this); 
     relativeLayout.addView(button); 

     Button button1 = new Button(this); 
     relativeLayout.addView(button1); 

     cardView.addView(relativeLayout); 
     linearLayoutCategory.addView(cardView); 
    } 

Это создает много CardView с хорошим позиционированным названием категории (TextView), но я не могу управлять, чтобы поместить описание категории. Эта линия не выглядит, чтобы иметь какое-либо влияние на textView1 (соответствует описанию категории):

 layoutParams3.addRule(RelativeLayout.BELOW, textView.getId()); 

Я не понимаю, потому что название категории хорошо позиционированы и я использовал ту же технику: addRule.
Я что-то забыл или допустил ошибку?
Адрес picture показать все объявления
Спасибо заранее.

ответ

2

Проблема заключается в том, что ваше правило основано на TextView ID:

layoutParams3.addRule(RelativeLayout.BELOW, textView.getId()); 

Но так как вы создать свой TextView из кода, он не имеет какой-либо идентификатор, присвоенный ему. В XML ваш TextView имеет id android:id="@+id/info_text", поэтому он отлично работает в XML.

Вам не нужно преобразовывать свой XML-макет в код - то, что вам нужно - просто надуть макет для каждой категории и добавить результат в контейнер (я считаю, что вы используете вертикальный LinearLayout в качестве контейнера для своих категорий) :

main_layout:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
      android:id="@+id/linearLayoutCategory" 
      android:orientation="vertical" 
      android:layout_width="match_parent" 
      android:layout_height="match_parent"> 

category.xml:

<?xml version="1.0" encoding="utf-8"?> 
    <android.support.v7.widget.CardView 
     xmlns:android="http://schemas.android.com/apk/res/android" 
     xmlns:card_view="http://schemas.android.com/apk/res-auto" 
     android:id="@+id/card_view" 
     android:layout_gravity="center" 
     android:layout_width="match_parent" 
     android:layout_height="200dp" 
     card_view:cardCornerRadius="4dp" 
     card_view:cardBackgroundColor="#00bcd4"> 

     <RelativeLayout 
      android:layout_width="match_parent" 
      android:layout_height="match_parent" 
      android:paddingBottom="@dimen/activity_vertical_margin" 
      android:paddingLeft="@dimen/activity_horizontal_margin" 
      android:paddingRight="@dimen/activity_horizontal_margin" 
      android:paddingTop="@dimen/activity_vertical_margin"> 

      <TextView 
       android:id="@+id/info_text" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:text="Category Name" 
       style="@style/Base.TextAppearance.AppCompat.Title" 
       android:paddingBottom="@dimen/activity_vertical_margin" 
       android:layout_centerHorizontal="true" /> 

      <TextView 
       android:layout_width="match_parent" 
       android:layout_height="match_parent" 
       android:text="Vel voluptatem soluta ipsa. Voluptatem est quod non explicabo aut quisquam quas. Voluptatem aliquam iure voluptas" 
       android:id="@+id/textView" 
       android:paddingBottom="@dimen/activity_vertical_margin" 
       android:layout_below="@+id/info_text" 
       android:layout_above="@+id/button"/> 

      <Button 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:text="Help" 
       android:id="@+id/button" 
       android:layout_alignParentBottom="true" 
       android:layout_alignParentEnd="true" /> 

      <Button 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:text="Play" 
       android:id="@+id/button2" 
       android:layout_alignParentBottom="true" 
       android:layout_alignParentStart="true" /> 

     </RelativeLayout> 
    </android.support.v7.widget.CardView> 

бизнес-логика:

LinearLayout linearLayoutCategory = (LinearLayout)findViewById(R.id.linearLayoutCategory); 
for (int i = 0; i < categories.size(); i++) { 
    View category = getLayoutInflater().inflate(R.layout.category, linearLayoutCategory, false); 

    TextView infoText = category.findViewById(R.id.info_text); 
    infoText.setText(/*category name?*/); 

    linearLayoutCategory.addView(category); 
}