I have created a sample project and run 'Hello Android Application' in Eclipse.
I have learned that a Textview can be created in two ways, either using an XML tag or by using Java code.
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.
This is what I have done:
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;
}
}
Further I don't know how to add this textview in addView()
.
This is my 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!
Set The Text of The TextView You can set the text to be displayed in the TextView either when declaring it in your layout file, or by using its setText() method. The text is set via the android:text attribute. You can either set the text as attribute value directly, or reference a text defined in the strings.
You write Android apps in the Java programming language using an IDE called Android Studio. Based on JetBrains' IntelliJ IDEA software, Android Studio is an IDE designed specifically for Android development.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With