如何解决上下文对话

时间:2018-09-03 14:03:31

标签: android android-fragments

如何解决Android Studio中的上下文问题?

public class NotesAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    MainFragment context;
    List<Note> noteList = new ArrayList<>();
}

public NotesAdapter(MainFragment context, List<Note> noteList) {
    this.context = context;
    this.noteList = noteList;
}

public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View v = LayoutInflater.from(context).inflate(R.layout.row_note, parent, false);

}

@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {

}

1 个答案:

答案 0 :(得分:0)

使用Recyclerview,您不需要通过构造函数传递上下文。

您可以使用ViewGroup父级并从那里获取上下文:

View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_note, parent, false);

所以您的适配器应如下所示:

List<Note> noteList = new ArrayList<>();

public NotesAdapter(List<Note> noteList) {
    this.noteList = noteList;
}

public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_note, parent, false);

}

@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {

}

希望对您有帮助。