2012-10-10 97 views
1

我试图创建自定义的ViewGroup类,但是当我使用的方法findViewById()它返回null,但膨胀的观点是好的。膨胀视图为空

代码是:

public class HorizontalListView extends ViewGroup 
{ 
    private int mNumber = 0; 
    private ImageView mImage; 
    private LinearLayout mAdapter; 

    public HorizontalListView(final Context context, final AttributeSet set) 
    { 
     super(context, set); 
     LayoutInflater.from(getContext()).inflate(R.layout.layout_horizontal_list_view, this, false); 

     mAdapter = (LinearLayout) getChildAt(0); 
    } 

    /**Adds ImageView to LinearLayout (Adapter) 
    * g 
    * @param image 
    */ 
    public void addView(final Bitmap image) 
    { 
     mImage = (ImageView) LayoutInflater.from(getContext()) 
            .inflate(R.layout.create_added_photo, null); 
     mImage.setImageBitmap(image); 
     mImage.setTag(mNumber); 
     mNumber++; 
     mAdapter.addView(mImage); 
    } 

    @Override 
    protected void onLayout(boolean changed, int l, int t, int r, int b) 
    { 
     // TODO Auto-generated method stub 

    } 

} 

这里mAdapter.addView(mImage);我有一个NullPointerException

XML代码:

<?xml version="1.0" encoding="utf-8"?> 
<HorizontalScrollView xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"> 

    <LinearLayout 
     android:orientation="horizontal" 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent" 
     android:gravity="center_vertical" 
     android:id="@+id/list_for_new_photos"> 

    </LinearLayout> 

</HorizontalScrollView> 
+1

检查“mAdapter”是否为空 – keyser

+1

您没有捕捉到虚增的视图。你只是在膨胀它,让GC收集它。将最后一个参数设置为“true”以将充气视图附加到当前视图。 – DeeV

+1

根据你的例子'getChildAt(0)'返回'Horizo​​ntalScrollView'而不是'LinearLayout' –

回答

2

如下

public HorizontalListView(final Context context, final AttributeSet set) { 
    super(context, set); 
    View view = LayoutInflater.from(getContext()).inflate(R.layout.layout_horizontal_list_view, this, false); 
    mAdapter = (LinearLayout) view.getChildAt(0); 
} 

public HorizontalListView(final Context context, final AttributeSet set) { 
    super(context, set); 
    View view = LayoutInflater.from(getContext()).inflate(R.layout.layout_horizontal_list_view, this, false); 
    mAdapter = (LinearLayout) view.findViewById(R.id.list_for_new_photos); 
} 
0

你mAdapter可能无法在Horizo​​ntalListView实例与getChildAt(0);线。

在那里您应该检查mAdapter是否为null,如果不可接受,则将其实例化为其他值。

如果mAdapter可以为null,那么在向它添加视图之前,必须先问问mAdapter是否为null。您无法将视图添加到空mAdapter。

0

请确保您有两个 “土地” 和 “布局” 文件夹中的布局xml文件更改代码。