Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inflating XML layout into a custom ViewGroup

I am trying to inflate xml layout into custom ViewGroup. After inflating the layout, ViewGroup only displays the root view of the layout in-fact it should display the full layout file into the ViewGroup.

I have gone through the other similar questions posted related to this on stackoverflow and other websites but none helped.

Here is the code of my custom ViewGroup:

public class ViewEvent extends ViewGroup {
private final String LOG_TAG="Month View Event";
public ViewEvent(Context context) {
        super(context); 
    }

    public ViewEvent(Context context,AttributeSet attrs) {
        super(context,attrs);   
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {      

        int childCount= getChildCount();
        for(int i=0;i<childCount;i++)
        {   
            Log.i(LOG_TAG, "Child: " + i + ", Layout [l,r,t,b]: " + l + "," + r + "," + t + "," + b);
            View v=getChildAt(i);
            if(v instanceof LinearLayout)
            {
                Log.i(LOG_TAG, "Event child count: " + ((ViewGroup)v).getChildCount()); // displaying the child count 1
                v.layout(0, 0, r-l, b-t);
            }
            //v.layout(l, r, t, b);
        }
    }   

In an Activity, I am using this custom view group:

ViewEvent event = new ViewEvent(getApplicationContext());
LayoutInflater inflator;
inflator=(LayoutInflater)appContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflator.inflate(R.layout.try1, event);
setContentView(event);

Following is the layout file:

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


    <TextView 
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:background="#ffff0000"
        android:text="asdasadfas" />

</LinearLayout>

After inflating this layout, I am only getting the root LinearLayout with backgroud color #ffff0000. TextView is not shown up.

Where I am doing wrong or missing something?

like image 751
Vinod Maurya Avatar asked Nov 14 '22 18:11

Vinod Maurya


1 Answers

try getParent() of event (your ViewEvent):

inflator.inflate(R.layout.try1, event.getParent(), false);
like image 161
Badre Avatar answered Jan 02 '23 11:01

Badre