gpt4 book ai didi

android - 膨胀 View 为空

转载 作者:行者123 更新时间:2023-11-29 21:57:38 25 4
gpt4 key购买 nike

我尝试创建自定义 ViewGroup 类,但是当我使用方法 findViewById() 时它返回 null,但展开 View 是可以的。

代码是:

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>

最佳答案

如下更改代码

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);
}

关于android - 膨胀 View 为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12822380/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com