kaid
kaid

Reputation: 1249

How to display Android UI via XML Layout?

Currently I understand I can create a XML Layout and pass that to setContentView(...), or I can pass a Customized view to setContentView(...).

But what if I want to combine the elements of both? Is it possible to use a layout first, then to programmatically add to the UI via java code?

For example: How could I create a view that uses an Asset background picture with an added loading widget on top?

ADDED INQUIRY: Right now and I think of a View and a Layout as two things for setContentView to display. But can a View hold a layout within it to be displayed?

Upvotes: 1

Views: 1628

Answers (2)

Ole
Ole

Reputation: 7989

Yes its possible to set an XML layout with setContentView(), and programmatically add more views/widget to that layout. Here's a short example.

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" 
    android:background="@drawable/background_image">

    <TextView 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Some text"/>

    <LinearLayout 
        android:id="@+id/custom_content_root"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
            android:orientation="vertical">

        <!-- This is where we will add views programmatically -->
    </LinearLayout>
</LinearLayout>

TestActivity.java

public class TestActivity extends Activity {
private LinearLayout mRoot;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Set the layout
    setContentView(R.layout.main);

    // Get the Linearlayout we want to add new content to..
    mRoot = (LinearLayout) findViewById(R.id.custom_content_root);

    // Create a TextView for example
    TextView moreText = new TextView(this);

    // Set the layout parameters of the new textview.
    moreText.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,  LayoutParams.WRAP_CONTENT));

    moreText.setText("More text :)");

    // Add the new textview to our existing layout
    mRoot.addView(moreText);
}
}

The result is an activity with background_image.png as background, and two textviews with text ;)

You can add any type of view (TextView, EditText, ImageView, Buttons etc) this way.

Upvotes: 1

Jords
Jords

Reputation: 1875

Yes, it is possible to add widgets after using setContentView(). It's also possible to inflate XML layouts yourself using LayoutInflater.

You could add the loading widget to a layout that was defined inside your XML by getting it using findViewById and then using a method from ViewGroup.

Upvotes: 0

Related Questions