Android - 动态添加行到布局

时间:2018-01-19 06:09:49

标签: android android-layout

我是Android新手。

请相应更改代码。

想要动态显示文本消息,所有这些都是异步调用,因为我从异步调用获得响应,我需要在屏幕上显示文本消息。它们可能与下面显示的顺序不同。

不应该等到所有异步调用完成并使用StringBuilder一起显示所有异步调用。这不是我要找的解决方案。

当我收到回复时,我需要逐行显示消息(如果可能的话,带一个小刻度标记)。线数不固定,可以是20或50。

感谢。

main.xml中

    <RelativeLayout
        android:id="@+id/llMessages"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal"
        android:visibility="visible">

        <TextView
            android:id="@+id/message"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="40dp"
            android:layout_marginTop="65dp"
            android:inputType="textMultiLine"
            android:singleLine="false"
            android:textIsSelectable="false"/>

    </RelativeLayout>

MainActivity.java

TextView msgs = findViewById(R.id.message);
msgs.setText("First\n"); 
msgs.setText("Second\n"); //<-- Text comes 3 seconds later - Async calls
msgs.setText("Third\n"); //<-- Text comes 3 seconds later - Async calls
msgs.setText("Fourth\n"); //<-- Text comes 3 seconds later - Async calls
msgs.setText("Fifth\n"); //<-- Text comes 3 seconds later - Async calls

2 个答案:

答案 0 :(得分:0)

每当有新文字可用时,使用此方法附加文字append()。把\ n换成新行

答案 1 :(得分:-1)

TextView中使用垂直方向的LinearLayout而不是xml。 用Java创建TextView

每次从服务器获取字符串时,在java中创建新的TextView并将其添加到LinearLayout中。 这是示例代码。

LinearLayout linearLayout =  (LinearLayout) findViewById(R.id.linear_layout_id);

TextView tv = new TextView(this);
tv.setText("FirstText");
tv.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT));

linearLayout.addView(tv);