問題描述
我創建了一個示例項目并在 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 并在其上顯示文本?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!