在Android Studio上动态生成TextView

3hvapo4f  于 11个月前  发布在  Android
关注(0)|答案(2)|浏览(219)

我是一个全新的Android Studio与Java,我只熟悉HTML,CSS,JavaScript和PHP。
我正在构建一个应用程序,我需要它从一个数组中生成一个项目列表。我该怎么做?
我试着简单地这样做,但在活动中什么也没有显示!
public void run(){

TextView t = new TextView(viewAuto.this);

    t.setTextColor(Color.RED);

字符串
“); }

mbyulnm0

mbyulnm01#

在Android中,在第一步中,您将调色板的每个功能放在xml中,您必须在java文件中像这样标识
TextView textView = findViewById(R.id.textView);
然后你就可以应用这些变化了。你所做的是从textView创建一个对象,这在材质设计的情况下是错误的。相反,它适用于类、片段、适配器等。

lztngnrs

lztngnrs2#

您需要首先创建XML布局和创建TextView组件

<?xml version="1.0" encoding="utf-8"?>
<androidx.appcompat.widget.LinearLayoutCompat xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/text_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</androidx.appcompat.widget.LinearLayoutCompat>

字符串
然后你去编码并获得文本视图,并使用\n附加所有字符串,以便在每个字符串的末尾都转到新行

class MainActivity : Activity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val textView = findViewById<R.id.text_view>()

        val yourList = listOf("Here", "Will", "Be", "Your", "Strings")

        yourList.forEach { textView.text = textView.text + it + "\n" }
    }

}


为了在可滚动列表中显示项目,您需要使用ScrollView,为了获得更好的性能,您需要使用RecyclerView

相关问题