androidtextviewandroid-linearlayout

How to add a TextView to a LinearLayout dynamically in Android?


I try to add a TextView to a LinearLayout dynamically such as in the following code, but it doesn't appear when I run the application?

setContentView(R.layout.advanced);

m_vwJokeLayout=(LinearLayout) this.findViewById(R.id.m_vwJokeLayout);
m_vwJokeEditText=(EditText) this.findViewById(R.id.m_vwJokeEditText);
m_vwJokeButton=(Button) this.findViewById(R.id.m_vwJokeButton);

TextView tv=new TextView(this);
tv.setText("test");
this.m_vwJokeLayout.addView(tv);

What's the problem?


Solution

  • LayoutParams lparams = new LayoutParams(
       LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    TextView tv=new TextView(this);
    tv.setLayoutParams(lparams);
    tv.setText("test");
    this.m_vwJokeLayout.addView(tv);
    

    You can change lparams according to your needs