我有两个适配器OperateClassroomAdapter和EditClassRoom适配器
public class OperateClassroomsAdapter extends RecyclerView.Adapter<OperateClassroomsAdapter.ViewHolder> {
private ArrayList<Classroom> classroomList;
private AdapterClickListener adapterClickListener;
public OperateClassroomsAdapter(ArrayList<Classroom> classroomList) {
this.classroomList = classroomList;
}
/**
* Set on item click listener
* @param adapterClickListener AdapterClickListener
*/
public void setAdapterClickListener(AdapterClickListener adapterClickListener) {
this.adapterClickListener = adapterClickListener;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.operate_classroom_item, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(ViewHolder viewHolder, final int position) {
Classroom item = classroomList.get(position);
viewHolder.text.setText(item.getName());
viewHolder.counter.setText(String.valueOf(item.getStudentNumber()));
Log.d("sn",String.valueOf(item.getStudentNumber()));
}
@Override
public int getItemCount()
{
return classroomList == null ? 0 : classroomList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView text;
TextView counter;
public ViewHolder(View itemView)
{
super(itemView);
itemView.setOnClickListener(this);
text = (TextView) itemView.findViewById(R.id.text);
counter = (TextView) itemView.findViewById(R.id.counter);
}
@Override
public void onClick(View v)
{
if (adapterClickListener != null) {
adapterClickListener.OnItemClick(getAdapterPosition());
}
}
}
}
在onBindViewHolder Log.d(&#34; sn&#34;)中显示正确的值,而在下面的代码中
public class EditClassroomsAdapter extends RecyclerView.Adapter<EditClassroomsAdapter.ViewHolder> {
private Context context;
private ArrayList<Classroom> classroomList;
private ListPopupWindow listPopupWindow;
private PopupClickListener popupClickListener;
private AdapterClickListener adapterClickListener;
private DeleteClassBtnClickListener deleteClassBtnClickListener;
private EditClassBtnClickListener editClassBtnClickListener;
private Random mRandom = new Random();
String colorarray[]= new String[]{
"#ffff66",
"#99ff66",
"#ffffff",
"#b3ffff",
"#ff8080",
"#ccdcff",
"#c3c3c3"
};
public EditClassroomsAdapter(Context context, ArrayList<Classroom> classroomList) {
this.context = context;
this.classroomList = classroomList;
listPopupWindow = new ListPopupWindow(context);
}
/**
* Set on item click listener
* @param adapterClickListener AdapterClickListener
*/
public void setAdapterClickListener(AdapterClickListener adapterClickListener) {
this.adapterClickListener = adapterClickListener;
}
/**
* Set on pop-up men item click listener
* @param popupClickListener PopupClickListener
*/
public void setPopupClickListener(PopupClickListener popupClickListener) {
this.popupClickListener = popupClickListener;
}
public void setDeleteClassBtnClickListener(DeleteClassBtnClickListener deleteClassBtnClickListener){
this.deleteClassBtnClickListener=deleteClassBtnClickListener;
}
public void setEditClassBtnClickListener(EditClassBtnClickListener editClassBtnClickListener) {
this.editClassBtnClickListener = editClassBtnClickListener;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.edit_classroom_item, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(final ViewHolder viewHolder, final int position) {
Classroom item = classroomList.get(position);
Log.d("sn22",String.valueOf(item.getStudentNumber()));
viewHolder.text.setText(item.getName());
viewHolder.student_count.setText(String.valueOf(item.getStudentNumber()));
viewHolder.settings.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (listPopupWindow != null) {
setListPopUpWindow(v, position);
}
}
});
/*
New Delete button added
*/
viewHolder.del_class.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(deleteClassBtnClickListener!=null)
deleteClassBtnClickListener.OnDeleteclassBtnClicked(position);
}
});
/*
edit_class button added
*/
viewHolder.edit_class.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(editClassBtnClickListener!=null)
editClassBtnClickListener.OnEditclassBtnClicked(position);
}
});
Random rand=new Random();
int rgen=rand.nextInt(6)+1;
viewHolder.thumbnail.getLayoutParams().height = getRandomIntInRange(350,200);
viewHolder.thumbnail.setBackgroundColor(Color.parseColor(colorarray[rgen]));
Glide.with(context).load(item.getThumbnail()).into(viewHolder.thumbnail);
// loading album cover using Glide library
// Glide.with(mContext).load(album.getThumbnail()).into(holder.thumbnail);
}
protected int getRandomIntInRange(int max, int min){
return mRandom.nextInt((max-min)+min)+min;
}
@Override
public int getItemCount() {
return classroomList == null ? 0 : classroomList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView text;
ImageButton settings;
ImageView thumbnail;
ImageButton del_class,edit_class;
TextView student_count;
public ViewHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
thumbnail=(ImageView) itemView.findViewById(R.id.cat_image) ;
text = (TextView) itemView.findViewById(R.id.text);
student_count = (TextView) itemView.findViewById(R.id.student_count);
settings = (ImageButton) itemView.findViewById(R.id.settings);
del_class=(ImageButton)itemView.findViewById(R.id.del_class);
edit_class=(ImageButton)itemView.findViewById(R.id.edit_class);
}
@Override
public void onClick(View v) {
if (adapterClickListener != null) {
adapterClickListener.OnItemClick(getAdapterPosition());
}
}
}
/**
* List pop up menu window
* @param anchor View
* @param classroomPosition List item's position
*/
private void setListPopUpWindow(View anchor, final int classroomPosition) {
listPopupWindow.dismiss();
listPopupWindow.setAdapter(new ArrayAdapter(context, android.R.layout.simple_list_item_1,
context.getResources().getStringArray(R.array.edit_classroom)));
listPopupWindow.setAnchorView(anchor);
listPopupWindow.setContentWidth(context.getResources()
.getInteger(R.integer.list_pop_up_width));
listPopupWindow.setDropDownGravity(Gravity.END);
listPopupWindow.setModal(true);
listPopupWindow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int menuItemPosition, long id) {
if (popupClickListener != null) {
popupClickListener.OnPopupClick(classroomPosition, menuItemPosition);
}
listPopupWindow.dismiss();
}
});
listPopupWindow.show();
}
}
Log.d(&#34; sn22&#34;)显示的值为0.为什么会发生这种情况?或者我如何从OperateClassroomAdapter获取值?
我的主要观点是即时通过相同的arraylist,仍然sn22显示0和其他显示正确的值。这些是2个不同的片段。 以下是各自使用它们的类的代码。
public class EditClassroomFragment extends Fragment {
private Context context;
private static int p=0;
private SwipeRefreshLayout swipeRefreshLayout;
private RecyclerView list;
private ArrayList<Classroom> arrayList = new ArrayList<>();
private EditClassroomsAdapter adapter;
private RecyclerView.LayoutManager mLayoutManager2 = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
private TextView emptyText; //empty list view text
public EditClassroomFragment() {}
public static EditClassroomFragment newInstance() {
EditClassroomFragment editClassroomFragment = new EditClassroomFragment();
return editClassroomFragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// retain this fragment
setRetainInstance(true);
}
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.refreshable_list, container, false);
context = rootView.getContext();
list = (RecyclerView) rootView.findViewById(R.id.list);
adapter = new EditClassroomsAdapter(context, arrayList);
list.setAdapter(adapter);
list.setLayoutManager(mLayoutManager2);
list.setHasFixedSize(true);
emptyText = (TextView) rootView.findViewById(R.id.emptyText);
swipeRefreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.swipeRefreshLayout);
swipeRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_bright,
android.R.color.holo_green_light,
android.R.color.holo_orange_light,
android.R.color.holo_red_light);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
new SelectClassrooms().execute();
}
});
addDeleteClassBtnClickListener();
addAdapterClickListener();
addPopupClickListener();
addEditClassBtnClickListener();
new SelectClassrooms().execute();
return rootView;
}
/**
* Set empty list text
*/
private void setEmptyText() {
if (emptyText != null) {
if (arrayList.isEmpty()) {
emptyText.setVisibility(View.VISIBLE);
} else {
emptyText.setVisibility(View.GONE);
}
}
}
/**
* Check if the given classroom name already exists
* @param classroomName Selected classroom
* @return
*/
private boolean isAlreadyExist(String classroomName) {
boolean isAlreadyExist = false;
for (Classroom classroom : arrayList) {
if (classroom.getName().equals(classroomName)) {
isAlreadyExist = true;
break;
}
}
return isAlreadyExist;
}
/**
* Add new class item
*/
public void addClassroom() {
final PromptDialog promptDialog = new PromptDialog(context);
promptDialog.setPositiveButton(getString(R.string.ok));
promptDialog.setAllCaps();
promptDialog.setAlphanumeric();
promptDialog.setOnPositiveClickListener(new PromptListener() {
@Override
public void OnPrompt(String promptText) {
closeKeyboard();
promptDialog.dismiss();
if (!TextUtils.isEmpty(promptText)) {
if (!isAlreadyExist(promptText)) {
new InsertClassroom().execute(promptText);
} else {
//alert
CustomAlertDialog customAlertDialog = new CustomAlertDialog(context);
customAlertDialog.setMessage(getString(R.string.couldNotInsertClassroom));
customAlertDialog.setPositiveButtonText(getString(R.string.ok));
customAlertDialog.showDialog();
}
}
}
});
promptDialog.show();
}
public void addClassroom2(String st) {
if(st.equals(null)==false) {
if (!isAlreadyExist(st)) {
new InsertClassroom().execute(st);
} else {
//alert
CustomAlertDialog customAlertDialog = new CustomAlertDialog(context);
customAlertDialog.setMessage(getString(R.string.couldNotInsertClassroom));
customAlertDialog.setPositiveButtonText(getString(R.string.ok));
customAlertDialog.showDialog();
}
}
}
/**
* Change the selected class name
* @param classroomId current classroom to be changed
* @param content current name of the classroom
*/
public void editClassroom(final int classroomId, String content) {
final PromptDialog promptDialog = new PromptDialog(context);
promptDialog.setContent(content);
promptDialog.setPositiveButton(getString(R.string.ok));
promptDialog.setAllCaps();
promptDialog.setAlphanumeric();
promptDialog.setOnPositiveClickListener(new PromptListener() {
@Override
public void OnPrompt(String promptText) {
closeKeyboard();
promptDialog.dismiss();
if (!TextUtils.isEmpty(promptText)) {
new UpdateClassroom().execute(String.valueOf(classroomId), promptText);
}
}
});
promptDialog.show();
}
/**
* Delete classroom
* @param classroom Selected classroom
*/
private void deleteClassroom(final Classroom classroom) {
//show alert before deleting
CustomAlertDialog customAlertDialog = new CustomAlertDialog(context);
customAlertDialog.setMessage(classroom.getName()
+ getString(R.string.sureToDelete));
customAlertDialog.setPositiveButtonText(getString(R.string.delete));
customAlertDialog.setNegativeButtonText(getString(R.string.cancel));
customAlertDialog.setOnClickListener(new OnAlertClick() {
@Override
public void OnPositive() {
new DeleteClassroom().execute(classroom.getId());
}
@Override
public void OnNegative() {
//do nothing
}
});
customAlertDialog.showDialog();
}
/**
* Go inside classroom to add, change or delete students
* @param classroom
*/
private void showStudents(Classroom classroom) {
Intent intent = new Intent(context, EditStudentActivity.class);
intent.putExtra("classroom", classroom);
startActivity(intent);
getActivity().overridePendingTransition(R.anim.move_in_from_bottom,
R.anim.stand_still);
}
/**
* List item click event
*/
private void addAdapterClickListener() {
adapter.setAdapterClickListener(new AdapterClickListener() {
@Override
public void OnItemClick(int position) {
if (arrayList != null && arrayList.size() > position) {
showStudents(arrayList.get(position));
Log.d("sn44",String.valueOf(arrayList.get(position).getStudentNumber()));
}
}
});
}
/**
* Pop-up menu item click event
*/
public void addPopupClickListener() {
adapter.setPopupClickListener(new PopupClickListener() {
@Override
public void OnPopupClick(int itemPosition, int menuPosition) {
if (arrayList != null && arrayList.size() > itemPosition) {
Classroom classroom = arrayList.get(itemPosition);
if (menuPosition == ClassroomPopup.CHANGE_NAME.getValue()) {
editClassroom(classroom.getId(), classroom.getName());
} else if (menuPosition == ClassroomPopup.DELETE_CLASSROOM.getValue()) {
deleteClassroom(classroom);
}
}
}
});
}
/*
Edit button and delete button listeners
*/
public void addDeleteClassBtnClickListener()
{
adapter.setDeleteClassBtnClickListener(new DeleteClassBtnClickListener() {
@Override
public void OnDeleteclassBtnClicked(int position) {
if (arrayList != null && arrayList.size() > position) {
Classroom classroom = arrayList.get(position);
deleteClassroom(classroom);
}
}
});
}
public void addEditClassBtnClickListener()
{
adapter.setEditClassBtnClickListener(new EditClassBtnClickListener() {
@Override
public void OnEditclassBtnClicked(int position) {
if (arrayList != null && arrayList.size() > position) {
Classroom classroom = arrayList.get(position);
editClassroom(classroom.getId(), classroom.getName());
}
}
});
}
/**
* Select classrooms from DB
*/
private class SelectClassrooms extends AsyncTask<Void, Void, ArrayList<Classroom>> {
@Override
protected void onPreExecute() {
swipeRefreshLayout.setRefreshing(true);
}
@Override
protected ArrayList<Classroom> doInBackground(Void... params) {
DatabaseManager databaseManager = new DatabaseManager(context);
ArrayList<Classroom> tmpList = databaseManager.selectClassrooms();
return tmpList;
}
@Override
protected void onPostExecute(ArrayList<Classroom> tmpList) {
swipeRefreshLayout.setRefreshing(false);
arrayList.clear();
if (tmpList != null) {
arrayList.addAll(tmpList);
adapter.notifyDataSetChanged();
setEmptyText();
}
}
}
/**
* Insert classroom name into DB
*/
private class InsertClassroom extends AsyncTask<String, Void, Boolean> {
@Override
protected Boolean doInBackground(String... params) {
String classroom = params[0];
DatabaseManager databaseManager = new DatabaseManager(context);
boolean isSuccessful = databaseManager.insertClassroom(classroom);
return isSuccessful;
}
@Override
protected void onPostExecute(Boolean isSuccessful) {
if (isSuccessful) {
new SelectClassrooms().execute();
}
}
}
/**
* Update classroom name in the DB
*/
private class UpdateClassroom extends AsyncTask<String, Void, Boolean> {
@Override
protected Boolean doInBackground(String... params) {
String classroomId = params[0];
String newName = params[1];
DatabaseManager databaseManager = new DatabaseManager(context);
boolean isSuccessful = databaseManager.updateClassroomName(classroomId, newName);
return isSuccessful;
}
@Override
protected void onPostExecute(Boolean isSuccessful) {
if (isSuccessful) {
new SelectClassrooms().execute();
}
}
}
/**
* Delete a classroom item from DB
*/
private class DeleteClassroom extends AsyncTask<Integer, Void, Boolean> {
@Override
protected Boolean doInBackground(Integer... params) {
int classroomId = params[0];
DatabaseManager databaseManager = new DatabaseManager(context);
boolean isSuccessful = databaseManager.deleteClassroom(classroomId);
return isSuccessful;
}
@Override
protected void onPostExecute(Boolean isSuccessful) {
if (isSuccessful) {
new SelectClassrooms().execute();
}
}
}
/**
* Closes keyboard for disabling interruption
*/
private void closeKeyboard(){
try {
InputMethodManager imm = (InputMethodManager)
getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
} catch (Exception ignored) {}
}
}
public class AttendancesFragment extends Fragment {
private Context context;
private SwipeRefreshLayout swipeRefreshLayout;
private RecyclerView list;
private ArrayList<Classroom> arrayList = new ArrayList<>();
private OperateClassroomsAdapter adapter;
private TextView emptyText; //empty list view text
public AttendancesFragment() {}
public static AttendancesFragment newInstance() {
AttendancesFragment attendancesFragment = new AttendancesFragment();
return attendancesFragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// retain this fragment
setRetainInstance(true);
}
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.refreshable_list, container, false);
context = rootView.getContext();
list = (RecyclerView) rootView.findViewById(R.id.list);
adapter = new OperateClassroomsAdapter(arrayList);
list.setAdapter(adapter);
list.setLayoutManager(new LinearLayoutManager(context));
list.setHasFixedSize(true);
emptyText = (TextView) rootView.findViewById(R.id.emptyText);
swipeRefreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.swipeRefreshLayout);
swipeRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_bright,
android.R.color.holo_green_light,
android.R.color.holo_orange_light,
android.R.color.holo_red_light);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
new SelectClassrooms().execute();
}
});
addAdapterClickListener();
new SelectClassrooms().execute();
return rootView;
}
/**
* Set empty list text
*/
private void setEmptyText() {
if (emptyText != null) {
if (arrayList.isEmpty()) {
emptyText.setVisibility(View.VISIBLE);
} else {
emptyText.setVisibility(View.GONE);
}
}
}
/**
* List item click event
*/
public void addAdapterClickListener() {
adapter.setAdapterClickListener(new AdapterClickListener() {
@Override
public void OnItemClick(int position) {
if (arrayList != null && arrayList.size() > position) {
Intent intent = new Intent(context, TakeAttendanceActivity.class);
intent.putExtra("classroom", arrayList.get(position));
startActivityForResult(intent, 0);
getActivity().overridePendingTransition(R.anim.move_in_from_bottom,
R.anim.stand_still);
}
}
});
}
/**
* Select classrooms from DB
*/
private class SelectClassrooms extends AsyncTask<Void, Void, ArrayList<Classroom>> {
@Override
protected void onPreExecute() {
swipeRefreshLayout.setRefreshing(true);
}
@Override
protected ArrayList<Classroom> doInBackground(Void... params) {
DatabaseManager databaseManager = new DatabaseManager(context);
ArrayList<Classroom> tmpList = databaseManager.selectClassroomsWithStudentNumber();
return tmpList;
}
@Override
protected void onPostExecute(ArrayList<Classroom> tmpList) {
swipeRefreshLayout.setRefreshing(false);
arrayList.clear();
if (tmpList != null) {
arrayList.addAll(tmpList);
adapter.notifyDataSetChanged();
setEmptyText();
}
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
Snackbar.make(list, getString(R.string.saved), Snackbar.LENGTH_LONG).show();
}
}
}
答案 0 :(得分:0)
如果您的问题是如何从适配器传递到另一个数据,您可以使用SharedPreferences
保存并从适配器获取数据到另一个。
希望这能帮到你