2

In Android, I'm used to setting layouts with the XML file

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

But you can also set the content using a View in Java

    // Create the text view
    TextView textView = new TextView(this);
    textView.setTextSize(40);
    textView.setText(message);

    // Set the text view as the activity layout
    setContentView(textView);

This has the side effect of not being able to use the layout file any more.

Is there anyway I can programatically set, for example, a text value and still use the layout.xml file?

user3037328
  • 25
  • 1
  • 4
  • Well, I don't think you can apply both to setContentView() in one Activity. – Spring Breaker Dec 09 '13 at 13:34
  • see this: http://stackoverflow.com/questions/3995215/add-and-remove-views-in-android-dynamically or http://stackoverflow.com/questions/4203506/how-can-i-add-a-textview-to-a-linearlayout-dynamically-in-android – Shayan Pourvatan Dec 09 '13 at 13:38

3 Answers3

5

Sure.

In your layout.xml file you must define an id of the main layout (android:id="@+id/mainLayout" ) and then you can do this:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ViewGroup mainView = (ViewGroup) findViewById(R.id.mainLayout);

    // Create the text view
    TextView textView = new TextView(this);
    textView.setTextSize(40);
    textView.setText(message);

    mainView.addView(textView);
}
Harshid
  • 5,701
  • 4
  • 37
  • 50
Renan Bandeira
  • 3,238
  • 17
  • 27
1

When you use setContentView(R.layout.activity_main), you are telling that the layout to be used is the xml layout file activity_main.

When you use setContentView(textView), it replaces the previous added xml layout file by the textView component.

You can declare your TextView in the layout file and then set the text programmatically.

TextView textView = (TextView) findViewById(R.id.textView);
textView.setTextSize(40);
textView.setText(message);
pedromendessk
  • 3,538
  • 2
  • 24
  • 36
-1

for example:

in layout.xml paste this code:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:id = "@+id/lblText"
        android:textSize="40"
        />

</RelativeLayout>

and, in you MainActivity :

public class MainActivity extends Activity 
{

    private TextView lblText;

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

        this.lblText = (TextView)findViewById(R.id.lblText);
        this.lblText.setText("your message");        
    }
}
javad
  • 833
  • 14
  • 37