我知道如何通过用户输入显示一些文本,但我感到困惑的是如何在我现在拥有的文本下面添加一个全新的文本 block (我想放一个新的文本 block ,因为我希望文本的大小不同)。现在,我显示“欢迎[用户输入]!”
在我的 Activity 文件中我有:
public class DisplayMessageActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the message from the intent
Intent intent = getIntent();
String message = " Welcome " + intent.getStringExtra(MainActivity.EXTRA_MESSAGE) + "!";
// Create the text view
TextView textView = new TextView(this);
textView.setTextSize(25);
textView.setText(message);
// Set the text view as the activity layout
setContentView(textView);
}
在我的 fragment.xml 文件中,我有:
<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:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context="com.example.myfirstapp.DisplayMessageActivity$PlaceholderFragment"
android:gravity="center_horizontal"
android:orientation="vertical"
android:weightSum="1">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal" />
<TextView
android:layout_width="wrap_content"
android:text="TEST"
android:layout_height="wrap_content" />
</LinearLayout>
在我从其他用户那里得到的反馈的帮助下,我在第二个“TextView”中也添加了 android:text="TEST"。而且我还在 LinearLayout 中添加了 android:orientation="vertical"。但是当我运行应用程序时,“测试”仍然没有出现!提前致谢。
最佳答案
您没有将您的布局与您的 Activity
相关联。相反,您在运行时添加一个 TextView
,它是在运行时创建的。这就是为什么只有一个 TextView
出现的原因。您必须使用 setContentView(R.layout.mylayout);
而不是 setContentView(textView);
,因此您的 Activity
会获取您的布局。
编辑:在您的布局中,将 id 添加到您的 TextViews
,这样您就可以从您的 Activity
代码访问它们,如下所示:
<TextView
android:id="@+id/myFirstTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="TEST1" />
<TextView
android:id="@+id/mySecondTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="TEST2" />
然后在您的 Activity
中,在 onCreate()
中:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_layout);
// Get the message from the intent
Intent intent = getIntent();
String message = " Welcome " + intent.getStringExtra(MainActivity.EXTRA_MESSAGE) + "!";
TextView textView1 = (TextView) findViewById(R.id.myFirstTextView);
TextView textView2 = (TextView) findViewById(R.id.mySecondTextView);
textView1.setTextSize(25);
textView1.setText(message);
}
关于android - 如何制作另一个文本 block ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24590060/