8

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!

2 Answers 2

15

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);
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks but I have another problem now. I understand how to make a new TextView dynamically, but I need to refer to it in another function (the text changes every time this function is called). But I can't access it when it's in the onCreate function. I tried to make it a class variable by putting it outside the onCreate function but it gets an error when initializing. Also, do I have to do "lView.addView(yaddayadda)" every time I change the text? Or will it display the changed text automatically? Thanks!
put the TextView as a member of the Activity. See my code above for an example
Thanks I'm getting really close now, one morrrrre thing if you can help :) Now when I do sentenceText.setText("bluh bluh") I'm getting a NullPointerException in LogCat. Isn't this because I'm setting it to null in the declaration?
You have to get a reference to the text view before you can use any of its functions. Declaring it in the root of the class allows it to be used by all the functions. In your on create, you should get a reference to the actual TextView. sentenceText = (TextView)findViewById(R.id.sentencetext);
8

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.