将XML布局扩展到自定义ViewGroup

时间:2011-08-19 05:36:38

标签: 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);
        }
    }   

Activity中,我正在使用此自定义视图组:

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

以下是布局文件:

<?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>

在对此布局进行充气后,我只使用背景颜色LinearLayout获取根#ffff0000TextView未显示。

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

2 个答案:

答案 0 :(得分:2)

尝试getParent()事件(您的ViewEvent):

inflator.inflate(R.layout.try1, event.getParent(), false);

答案 1 :(得分:-1)

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

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

然后访问此TextView,如下所示。

TextView testTextView = (TextView) ViewEvent.findViewById(R.id.testTextId);
相关问题