开发者

Dynamically Display String text on Android Screen

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!


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜