Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inflating layout in custom control - how?

I've got and idea on how to create custom control here: Android interface - need suggestions on what widgets to use

How do I make the SAME but creating control's layout in XML and just inflating it in code? Not like in this example where I have to create each control manually.

My first problem that LinearLayout that used as a base does not support setView() command. Should I extend something else?

EDIT: I found This: http://developer.android.com/guide/topics/ui/custom-components.html and this: http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/view/List4.html

Seems like I need COMPOUND CONTROL. I just need little bit of code. How do I inflate control's content from XML? BOth article and sample say I can but HOW?

like image 439
katit Avatar asked May 05 '11 17:05

katit


People also ask

What is inflating a layout?

In this context, Inflate means reading a layout XML (often given as parameter) to translate them in Java code. This process happens: in an activity (the main process) or a fragment.

What is custom layout in Android?

Android provides a series of different layouts to suit your apps needs. One of the quickest and easiest ways to display information to users is via the ListView component. This component creates a simple scrollable region that can display unique sets of information.


1 Answers

You have to use a layout like this:

<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android">
  <View android:layout_width="fill_parent"
  android:layout_height="0px"
  android:layout_weight="1"
  android:background="#0F0"/>
  <View android:layout_width="fill_parent"
  android:layout_height="0px"
  android:layout_weight="1"
  android:background="#0FF"/>
</merge>

where <merge> means "put everything that's inside me into the parent I'm going to be inflated to".

Then in code:

public class CControl extends LinearLayout {

    public CControl(Context context) {
        this(context, null);
    }

    public CControl(Context context, AttributeSet attrs) {
        super(context, attrs);

        LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        inflater.inflate(R.layout.tryout, this);
    }
    // ......
}

At this point you can use your compound control as if it's a LinearLayout, so you'll have to specify in the outer layout if you want it to be vertical, for example, or you could set it as a default inside the constructor.

like image 98
bigstones Avatar answered Oct 17 '22 17:10

bigstones