Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically Display String text on Android Screen

Tags:

android

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.

Thanks!

like image 801
datWooWoo Avatar asked Jun 29 '11 19:06

datWooWoo


2 Answers

To add a view dynamically. Use the addView function.

public MyActivity extends Activity {
  private TextView myText = null;

  @Override
  public onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.id.mylayout);

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

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

     lView.addView(myText);
}

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");

lView.addView(myText);

setContentView(lView);
like image 147
Spidy Avatar answered Nov 09 '22 22:11

Spidy


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();
like image 42
SBerg413 Avatar answered Nov 09 '22 20:11

SBerg413