简体   繁体   中英

setContentView() with XML layout vs View

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?

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM