如何获取我在 .java 文件中创建的字符串以显示在应用程序 UI 上?
在 Android 中,任何向用户展示某物的东西都称为视图。有很多不同的类型,适合可视化不同类型的数据。对于基本文本,您需要TextView。所以简化一些事情,让我们假设您拥有链接中显示的 XML 代码:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
</LinearLayout>
有许多资源可以解释如何构建/使用布局、它们的优缺点,所以我跳过了这一部分。需要意识到的重要一点是在上述布局中定义了一个TextView。为了引用它,它需要有一个唯一的 id。让我们添加一个:
<TextView
android:id="@+id/question_textview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
然后您可以从 Java 代码中引用此 TextView,如下所示:
TextView questionTextView = (TextView) findViewById(R.id.question_textview);
请注意,R.id.question_textview 基本上就是我们之前在布局中命名的 TextView。从这里开始,您就有了一个 Java 对象,您可以用它做各种事情,包括获取和设置它所显示的文本。
String textDisplayed = questionTextView.getText(); // This will get the text currently displaying.
questionTextView.setText("Please display me"); // This will set the displayed text to "Please display me".
我真的建议您阅读更多教程和 api 演示,因为这是非常基础的东西。