我正在developer.android.com上关注“构建您的第一个应用程序”的教程,并对如何在活动和XML布局之间传递信息提出疑问。
我有每个活动的布局:
Here are pictures of the layouts I am using. 左边的那个是主要活动,而右边的那个是按下“发送”按钮时启动的辅助活动。
我希望应用程序将主活动中的EditText小部件的消息输入传递给辅助活动中的TextView,同时保持我当前为辅助活动设置的图片和背景格式。
developer.android网站上“构建您的第一个应用程序”教程的“启动另一个活动”部分仅显示如何使用在Java中定义的TextView将消息传递给辅助活动,同时忽略XML布局。
如何将消息转发到我的XML布局,或者如何将Java中定义的TextView以及XML布局合并?
Here is all my code for the activities' XML and JAVA files 很抱歉这个巨大的转储,但是这个网站现在不允许我发布超过两个链接
我尝试在该活动java文件中引用辅助活动的TextView,然后从那里设置文本,但是当我这样做时我的程序崩溃了。
任何帮助将不胜感激。谢谢!
答案 0 :(得分:1)
而不是在第二项活动中制作全新的TextView
:
TextView textView = new TextView(this);
您应该在第二个活动布局文件中为TextView
元素添加一个id:
<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:background="@color/yellow"
android:orientation="vertical" >
<TextView
android:id="@+id/text_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="20dp"
android:background="@color/white"
android:text="message" />
<ImageView
android:src="@drawable/open"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
在设置内容视图后,您可以在第二个活动的代码中引用这个TextView
:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_message);
Intent intent = getIntent();
String message = intent.getStringExtra(MyActivity.EXTRA_MESSAGE);
// must call this after setting the content view;
// otherwise, textView will still be null.
TextView textView = (TextView) findViewById(R.id.text_view);
textView.setTextSize(40);
textView.setText(message);
}