我正在创建 Android 游戏,但在使用 TextView 的动态文本方面遇到问题。在我的布局中,我有一个 TextView,它位于一个相对布局中,有足够的空间容纳几行。
我想做的是在 TextView 中添加 5 行,其功能是一旦尝试写入第 6 行,它就会自动覆盖第 1 行,因此最多只显示 5 行文本。
我所追求的示例:
dynamic line 1
...
dynamic line 5
请在下面找到我的 xml 代码:
<RelativeLayout android:id="@+id/battleconsole"
android:layout_width="fill_parent"
android:layout_height="135dp"
android:gravity="center_horizontal"
android:layout_below="@+id/spacer1" >
<TextView
android:id="@+id/battle_details"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="Console with information" />
</RelativeLayout>
这是我用来更新 TextView 中文本的代码:
TextView update = (TextView)findViewById(R.id.battle_details);
update.setText("test console data going in here");
我不确定使用 TextView 是否可以,如果不行,还有其他方法可以解决这个问题吗?
提前致谢
最佳答案
将 5 行保留在集合(数组或列表)中。当您在 TextView 上设置文本时,将集合中的行连接到“\n”上。然后只需用更新的文本替换集合中的项目即可。
Android 在 TextUtils 类中有一个 join 方法,但我更喜欢 Guava 库的 Joiner 类。看看:Google Guava
关于java - Android - 创建动态 TextView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12919535/