在片段中初始化视图时,在getcontext()处出现nullpointerException

时间:2019-01-25 17:37:06

标签: java android android-fragments android-view android-context

我正在DailyCardView.java初始化imageview,它由一个片段调用。但它一直显示nullPointerException。我真的不知道哪里出了问题...伙计们帮我> << / p>

我尝试使用getRootView()获取Fragment的视图,因此我可以编写代码:iv =(ImageView)getRootView()。findViewById(R.id.iv); 但这仍然行不通。

**//Fragment**
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.home_fragment, container, false);
    dailyStackLayout = (DailyStackLayout)view.findViewById(R.id.dailyStackLayout);
    dailyStackLayout.setDatas(dailyFoodList);
    return view;
}

**//DailyStackLayout**
public DailyStackLayout(Context context) {
    this(context, null);
}
public DailyStackLayout(Context context, AttributeSet attrs) {
    this(context, attrs, 0);
}
public DailyStackLayout(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    init();
}

public void init() {
    params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    scaleY = DensityUtil.dip2px(getContext(), BASESCALE_Y_VALUE);
}
public void setDatas(List<DailyFood> dailyFoodList) {
    this.dailyFoodList = dailyFoodList;
    if (dailyFoodList == null) {
        return;
    }
    for (int i = index; index < i + STACK_SIZE; index++) {
        dc = new DailyCardView(getContext());
        dc.bind(dailyFoodList.get(index));
    }
}

**//DailyCardView**
public DailyCardView(Context context) {
    super(context, null);
}
public DailyCardView(Context context, AttributeSet attrs) {
    this(context, attrs,0);
}

public DailyCardView(Context context, AttributeSet attrs, int defStyleAttr) 
{
    super(context, attrs, defStyleAttr);
    init(context);
}

public void init(Context context) {
    if (!isInEditMode()) {
        inflate(context, R.layout.item_daily_card, this);
        iv = (ImageView)findViewById(R.id.iv);
    }
}
public void bind(DailyFood dailyFood) { 
    if (dailyFood == null) {return;}
    if (!TextUtils.isEmpty(dailyFood.getId())) {
        Glide.with(**iv.getContext()**)  // **NullPointerException**!
                .load(Constant.Daily_URL+dailyFood.getId()+".jpg")
                .into(iv);
}

我希望正确加载图像,但在getContext()时出错。

1 个答案:

答案 0 :(得分:0)

dc = new DailyCardView(getContext());

这将调用DailyCardView(Context)构造函数,而该构造函数不会调用init()

public DailyCardView(Context context) {
    super(context, null);
}

init()调用将初始化iv。然后调用bind(),假设iv已初始化。邦,NPE。

或者将构造函数中的super更改为this,以委托给另一个调用init()的构造函数,或者只添加对init()的调用。