gpt4 book ai didi

android - RecyclerView 中的 setLayoutManager NullPointErexception

转载 作者:IT王子 更新时间:2023-10-28 23:36:17 24 4
gpt4 key购买 nike

我正在尝试在 RecyclerView 中接收包含数组的列表并收到错误:

java.lang.NullPointerException: Attempt to invoke virtual method 
'void android.support.v7.widget.RecyclerView.setLayoutManager
(android.support.v7.widget.RecyclerView$LayoutManager)'on a null object reference

RecyclerView 小部件的

   <android.support.v7.widget.RecyclerView
android:id="@+id/drawerList"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</android.support.v7.widget.RecyclerView>

我尝试将 LayoutManager 声明为 final,但没有帮助。

Activity 代码:

public class MainActivity extends ActionBarActivity {

private RecyclerView recyclerView;
private Toolbar toolbar;
private InfAdapter adapter;


@Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
setContentView (R.layout.activity_main_appbar);

recyclerView = (RecyclerView) findViewById(R.id.drawerList);

recyclerView.setLayoutManager(new LinearLayoutManager(this));

InfAdapter mAdapter = new InfAdapter(this, getData());
recyclerView.setAdapter(mAdapter);
recyclerView.setItemAnimator(new DefaultItemAnimator());

toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);

}

适配器代码:

public class InfAdapter extends RecyclerView.Adapter<InfAdapter.MyViewHolder> {

private final Context context;
private List<Information> data = Collections.emptyList();


public InfAdapter(Context context, List<Information> data){
this.data = data;
this.context = context;
}

@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.custom_row, parent, false);
return new MyViewHolder(v);
}


@Override
public void onBindViewHolder(MyViewHolder holder, int position) {

Information current = data.get(position);
holder.title.setText(current.title);
holder.icon.setImageResource(current.iconid);
}


@Override
public int getItemCount() {
return data.size();
}

class MyViewHolder extends RecyclerView.ViewHolder{
TextView title;
ImageView icon;

public MyViewHolder(View itemView) {

super(itemView);
title = (TextView) itemView.findViewById(R.id.listText);
icon = (ImageView) itemView.findViewById(R.id.listIcon);

}
}
}

可能出了什么问题?

最佳答案

正如@StenSoft 在评论中指出的那样,问题出在setContentView(R.layout.activity_main_appbar); 因为activity布局内容错误,而不是setContentView(R.layout.activity_main);

关于android - RecyclerView 中的 setLayoutManager NullPointErexception,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28570842/

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