【问题标题】:Inflating XML layout into a custom ViewGroup将 XML 布局膨胀到自定义 ViewGroup
【发布时间】:2011-08-19 05:36:37
【问题描述】:

我正在尝试将 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 没有显示出来。

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

【问题讨论】:

    标签: android android-layout viewgroup


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      试试这样。你没有为你的 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);
      

      【讨论】:

      • 可以访问但不显示!
      猜你喜欢
      • 2012-06-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多