[英]Basic issue with Java/Android
几天前,我开始学习Java,因此我对此非常迷惑。 我想显示从一个意图接收到的文本,并使它看起来像这样:“您已经写了:”。 它根本不起作用,我只能从意图中显示文本。
这是我的代码:
// Create the text view
TextView textView = new TextView(this);
textView.setTextSize(40);
System.out.print("You've written: ");
textView.setText(message);
System.out.print(".");
// Set the text view as the activity layout
setContentView(textView);
}
此外,我正在尝试在页面的第一行(或需要的多行)中显示上方书写的文本,以及在下方显示用于将文本与Button一起插入的标签。 问题是我只能从意图中看到文本。 这是我的代码:
<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".DisplayMessageActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
<EditText android:id="@+id/edit_message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="@string/edit_message" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button_send"
android:onClick="sendMessage"/>
</RelativeLayout>
非常感谢,我希望尽快得到答复。
而不是System.out.println。
这样吧
<TextView
android:id="@+id/topTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
并获取活动视图。
public void onCreate(Bundle bundle) {
.........
setContentView(layout_xml);
TextView textView = (TextView)findViewById(R.id.topTextView);
textView.setText("You've written: " + message + " .");
.........
}
如果您尝试在布局内引用TextView,则需要在Activity中对其进行引用。 上面的解决方案显示了如何处理。 setContentView(R.layout.file_name)是用来引用在存储在res / layout / file_name.xml中的xml文件中创建的布局或在代码内部手动创建的布局的内容。 如果要为(Activity)内部构造的布局调用setContentView,则将需要更多代码。 如果只需要显示消息,则可以随时调用Toast.maketText(Context,message,Toast.LENGTH_SHORT).show();。 例如。 另一个建议是Java开发人员习惯于使用System.out.println()调试控制台。 在Android中,它们具有一项整洁的功能,我们使用称为LogCat的功能,它可以通过说出Log.d(TAG,message)(例如,用于调试目的的示例)来显示代码内部发生的消息。 TAG通常是您为Activity,Fragment等定义的常量,因此您可以查看消息的来源并显示通常在System.out.println()中使用的任何值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.