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がnullであるかどうかを確認し、それが受け入れられない場合は、他の何かにインスタンス化する必要があります。

mAdapterがnullであっても問題がない場合は、ビューを追加する前に、mAdapterがnullかどうかを確認する必要があります。nullmAdapterにビューを追加することはできません。

于 2012-10-10T15:04:21.117 に答える