将XML布局扩展到自定义ViewGroup

Vin*_*rya 5 android android-layout viewgroup

我试图将xml布局扩展为自定义ViewGroup.在给布局膨胀之后,ViewGroup只显示布局的根视图,实际上它应该将完整的布局文件显示到ViewGroup.

我在stackoverflow和其他网站上经历了与此相关的其他类似问题,但没有帮助.

这是我的自定义代码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);
        }
    }   
Run Code Online (Sandbox Code Playgroud)

在一个Activity,我使用这个自定义视图组:

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

以下是布局文件:

<?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>
Run Code Online (Sandbox Code Playgroud)

在膨胀这个布局之后,我只LinearLayout使用背景颜色获得根#ffff0000.TextView没有出现.

我做错了什么或遗失了什么?

jai*_*nal -1

尝试这样。您没有为 TextView 声明任何 id。

   <TextView 
            android:id="@+id/testTextId"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:background="#ffff0000"
            android:text="asdasadfas" />
Run Code Online (Sandbox Code Playgroud)

然后像下面这样访问这个 TextView。

TextView testTextView = (TextView) ViewEvent.findViewById(R.id.testTextId);
Run Code Online (Sandbox Code Playgroud)