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

3 回答 3

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);
}
于 2012-10-10T15:27:40.170 回答
0

您的 mAdapter 可能不会在 Horizo​​ntalListView 中用该getChildAt(0);行实例化。

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

如果 mAdapter 可以为空,那么在向其添加视图之前,您必须先询问 mAdapter 是否为空。您不能将视图添加到空 mAdapter。

于 2012-10-10T15:04:21.117 回答
0

确保在“land”和“layout”文件夹中都有布局 xml 文件。

于 2017-05-18T16:24:45.947 回答