2017-02-09 3 views
-2

В основном, я читал сообщения из базы данных firebase один за другим в цикле, после чего я хочу добавить каждое сообщение в линейный макет.Динамически создавать линейную компоновку

У меня есть Linear Layout XML файл, как этот называется my_linear_layout IMAGE SAMPLE

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout 
android:layout_width="match_parent" 
android:layout_height="wrap_content" 
android:layout_below="@+id/layout2" 
android:layout_marginTop="20dp" 
android:orientation="horizontal" 
xmlns:android="http://schemas.android.com/apk/res/android"> 

<TextView 

    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_marginTop="10dp" 
    android:layout_weight="6" 
    android:background="@drawable/rounded_corner" 
    android:padding="16dp" 
    android:text="MESSAGE GOES HERE. IT CAN BE A LOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOONG MESSAGE" 
    android:textColor="#000" /> 


<ImageView 

    android:layout_width="40dp" 
    android:layout_height="40dp" 
    android:layout_marginTop="0dp" 
    android:layout_weight="3" 
    android:src="@drawable/senduser" /> 

</LinearLayout> 

Теперь хочу раздувать этот макет в моем Relative Layout Activity в

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:tools="http://schemas.android.com/tools" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:background="#ffffff" 
android:orientation="vertical" 
tools:context=".BuyerChat"> 

<ScrollView 
    android:layout_width="match_parent" 
    android:layout_weight="20" 
    android:layout_height="wrap_content"> 

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


    </RelativeLayout> 
</ScrollView> 

<include 
    layout="@layout/type_message_area" 
    android:layout_width="match_parent" 
    android:layout_weight="1" 
    android:layout_height="wrap_content" 
    android:gravity="bottom" /> 
</LinearLayout> 

Я не могу просто добавить код здесь, потому что я хочу иметь n число линейных макетов, в зависимости от того, сколько сообщений у меня есть. В основном, я читаю сообщения из базы данных firebase, после чего я хочу добавить каждое сообщение в линейный макет.

Итак, я хочу фрагмент кода, который позволит мне добавлять линейный макет каждый раз, когда я его вызываю, и размещать новое сообщение в линейной компоновке каждый раз.

Я был в этом довольно долгое время, пожалуйста, помогите.

+0

То, что вы пробовали до сих пор? – Selvin

+0

@Selvin Я попробовал метод, показанный здесь: http: //androidexample.com/Dynamically_Create_View_Elements__-_Android_Example/index.php? View = article_discription & aid = 115 Но я не знаю, как установить ширину отображения макета и текста как wrap_content или match_parent через java. – theBrainyGeek

ответ

1

Вы можете сделать так:

<?xml version="1.0" encoding="utf-8"?> 
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:background="#ffffff" 
    android:orientation="vertical" 
    tools:context=".BuyerChat"> 

    <ScrollView 
     android:layout_width="match_parent" 
     android:layout_weight="20" 
     android:layout_height="wrap_content"> 

     <LinearLayout 
      android:id="@+id/dynamic_holder" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:orientation="vertical" 
      android:paddingBottom="@dimen/activity_vertical_margin" 
      android:paddingLeft="@dimen/activity_horizontal_margin" 
      android:paddingRight="@dimen/activity_horizontal_margin" 
      android:paddingTop="@dimen/activity_vertical_margin"> 


     </LinearLayout> 
    </ScrollView> 

    <include 
     layout="@layout/type_message_area" 
     android:layout_width="match_parent" 
     android:layout_weight="1" 
     android:layout_height="wrap_content" 
     android:gravity="bottom" /> 
    </LinearLayout> 

А в вашей деятельности:

LinearLayout dynamicHolder = (LineraLayout) findViewById(R.id.dynamic_holder); 

for(int i = 0; i<your_message_length; i++){ 
    View dynamicView = LayoutInflater.from(context).inflate(R.layout.my_linear_layout, null, false); 
    TextView yourTextView = (TextView) dynamicView.findViewById(R.id.your_tv_id);//give id to your textview in my_linear_layout 
    youtTextView.setText(your_each_message_from_db); 

    dynamicHolder.addView(dynamicView); 
} 
0

Почему вы используете линейный макет вместо ListView.
В этом случае настоятельно рекомендуется ListView.

См. here Насколько эффективны listViews по сравнению с linearLayout.
Плюс его проще в использовании.
ListViews не раздувают все предметы, они раздуваются, однако многие могут поместиться на странице за раз. Самый быстрый вариант с пейджингом или без него - это ListView.

См. Здесь, как начать работу с приложением listView для чата.
Simple chat application using listview in android

Я предлагаю вам создать пользовательский адаптер для ListView. Вам просто нужно проверить условие, чтобы изменить фон макета/представлений внутри метода getViews().

Некоторые нити могут быть полезны для вас:

The World of List View
Android Implementing Chat Bubble in ListView

Смежные вопросы