Mitch Zinck
Mitch Zinck

Reputation: 312

Programmatically set a textview in Android

I currently have:

final TextView tv = new TextView(this); 
final RelativeLayout rL = new RelativeLayout(this);
final EditText editText = (EditText)findViewById(R.id.editText);   
final Button b1 = (Button)findViewById(R.id.b1);    

 b1.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            rL.addView(tv);
            tv.setText(editText.getText());
            editText.setText("");

        }
    });

In my onCreate method but my textView does not show up on the screen when text is inputted and my button is pressed? Is there code to set where it is set up on the screen of my phone?

Upvotes: 0

Views: 129

Answers (2)

Shellum
Shellum

Reputation: 3179

Do you have a base layout? You're adding the EditText to the RelativeLayout, but you need to add the RelativeLayout to some already existing layout.

First, inflate some base layout. Then do a findViewById on that layout. Use this to call addView(editText);

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/base_layout"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
</RelativeLayout>



public class MyActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout);

        RelativeLayout rl = (RelativeLayout)findViewById(R.layout.base_layout);
        rl.addView(yourTextView);

    }

}

Upvotes: 1

anthonycr
anthonycr

Reputation: 4186

Here is your problem

final RelativeLayout rL = new RelativeLayout(this);

This RelativeLayout that contains the TextView is not even displayed on the screen, all you are doing is creating a RelativeLayout.

What you should do instead is add a RelativeLayout to your XML layout file (same one containing the EditText and Button and do the following

final RelativeLayout rL = (RelativeLayout)findViewById(R.id.myRelativeLayout);
...
rL.addView(tv);

Now since you are referencing an actual RelativeLayout, your text will be visible. Hope I made some sort of sense.

Upvotes: 2

Related Questions