Home » Android » Dynamically Display String text on Android Screen

Dynamically Display String text on Android Screen

Posted by: admin June 15, 2020 Leave a comment


I have an array of classes that contain two strings for each class. I’m trying to display these two strings (they’re sentences) on the screen when a button is clicked at two different locations (middle of the screen, and the other sentence right above that).

The problem is that I only know how to get text on the screen through the XML layout file, not dynamically. How would I go about doing this? I already have the buttons and background done in XML.


How to&Answers:

To add a view dynamically. Use the addView function.

public MyActivity extends Activity {
  private TextView myText = null;

  public onCreate(Bundle savedInstanceState) {

     LinearLayout lView = (LinearLayout)findViewById(R.id.mylinearlayout);

     myText = new TextView();
     myText.setText("My Text");


If you don’t want to use an xml file at all:

//This is in the onCreate method
LinearLayout lView = new LinearLayout(this);

myText = new TextView(this);
myText.setText("My Text");




It’s not totally clear how you want to display the text, BUT you most certainly could use a Toast message:

Toast.makeText(getApplicationContext(), "Sample Text", Toast.LENGTH_LONG).show();