Add text dynamically - Android

How can I dynamically add a TextView to this? Commented code does not work.

public class myTextSwitcher extends Activity { private TextView myText; public myTextSwitcher(String string){ //myText = new TextView(this); //myText.setText("My Text"); } } 
+3
source share
4 answers

You create a text view and set its value, but do not specify where and how it should be displayed. Your myText object must have a container that makes it visible.

What you are trying to do is dynamically expand the view. See here for a good article for beginners . From the article:

 // This is where and how the view is used TextView tv = new TextView(this); tv.setText("Dynamic layouts ftw!"); ll.addView(tv); // this part is where the containers get "wired" together ScrollView sv = new ScrollView(this); LinearLayout ll = new LinearLayout(this); ll.setOrientation(LinearLayout.VERTICAL); sv.addView(ll); 
+4
source

First of all, you should not add it to the constructor, and non-default constructors are practically useless for Activity . Finally, you correctly create a new TextView , but do not add it anywhere. Get some layout in your content view (possibly with findViewById ) and call layout.addView(myText) with it.

+1
source

You added your text view to the action using setContentView(myText);

do it

 myText = new TextView(this); myText.setText("foo"); setContentView(myText); 
0
source

in oncreate () method

  final TextView tv1 = new TextView(this); tv1.setText("Hii Folks"); tv1.setTextSize(14); tv1.setGravity(Gravity.CENTER_VERTICAL); LinearLayout ll = (LinearLayout) findViewById(R.id.lin); ll.addView(tv1); 

Your activity_main.xml

 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/lin" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center_vertical|center_horizontal" android:orientation="horizontal"> </LinearLayout> 
0
source

Source: https://habr.com/ru/post/1489070/


All Articles