问题描述
我创建了一个示例项目并在 Eclipse 中运行Hello Android Application".
I have created a sample project and run 'Hello Android Application' in Eclipse.
我了解到可以通过两种方式创建 Textview,使用 XML 标记或使用 Java 代码.
I have learned that a Textview can be created in two ways, either using an XML tag or by using Java code.
默认情况下,我的示例项目中有一个 Textview 说Hello world".我想使用 Java 代码创建一个 Textview 并在上面显示一些消息.
By default I have one Textview saying "Hello world" in my sample project. I want to create a Textview using Java code and display some message on it.
我查了很多,但无法理解代码中提到的步骤和布局设置.
I have searched a lot, but I am unable to understand the steps and layout settings mentioned in the code.
这就是我所做的:
import android.app.Activity;
import android.view.Menu;
import android.view.ViewGroup;
import android.widget.*;
import android.view.View;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout.LayoutParams params =
new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT, 0.0F);
TextView tx= new TextView(this);
// tx.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
tx.setText("ANDROID APP");
lay
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
另外我不知道如何在 addView()
中添加这个 textview.
Further I don't know how to add this textview in addView()
.
这是我的 activity_main.xml
:
<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"
tools:context=".MainActivity" >
</RelativeLayout>
一步一步的解决方案对我很有帮助,任何好的教程链接都会很有价值.提前谢谢!
A step by step solution would be helpful for me and any good tutorial link would be appreciable. Thank you in advance!
推荐答案
使用这段代码,创建文本视图并设置布局参数
Use this code, Create text view and set layout params
TextView dynamicTextView = new TextView(this);
dynamicTextView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
dynamicTextView.setText(" Hello World ");
将此文本视图添加到主布局
add this textview to the main layout
mainlayout.addView(dynamicTextView);
这篇关于如何使用 java 代码创建简单的 Android TextView 并在其上显示文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!