我需要发送ArrayList list_add到活动中,但是我不知道如何在可能的情况下与主要活动共享以便将来使用。 有人可以帮助我实现此方法吗? 下面有用于recyclerview的MainAdatper,其中我有一个list_add并想将其传递给主要活动,然后将其添加到
class MainAdapter extends RecyclerView.Adapter <MainAdapter.ViewHolder> {
private static int lastCheckedPos = 0;
ArrayList<String> list_add = new ArrayList<>();
ArrayList<String> lista_show;
private Context context;
String t;
public MainAdapter(ArrayList<String> lista_shows, Context context) {
lista_show = lista_shows;
}
@Override
public MainAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from (parent.getContext ()).inflate (R.layout.row,parent,false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(final MainAdapter.ViewHolder holder, final int position) {
holder.mdevice.setText (lista_show.get (position));
holder.cardView.setOnLongClickListener (new View.OnLongClickListener () {
@Override
public boolean onLongClick(View v) {
t = lista_show.get(position);
if (list_add.contains(t)) {
Toast.makeText(v.getContext (), t+"Already Selected", Toast.LENGTH_SHORT).show();
} else {
list_add.add(t);
holder.cardView.setCardBackgroundColor(Color.parseColor("#60B5EC"));
Toast.makeText(v.getContext (), t+"Added", Toast.LENGTH_SHORT).show();
}
return true;
}
});
holder.cardView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
t = lista_show.get (position);
holder.cardView.setCardBackgroundColor(Color.WHITE);
if (! list_add.contains(t)) {
Toast.makeText(v.getContext (), "Long press for add", Toast.LENGTH_SHORT).show();
} else {
list_add.remove(t);
Toast.makeText(v.getContext (), t+"Removed", Toast.LENGTH_SHORT).show();
}
}
});
}
@Override
public int getItemCount() {
return lista_show.size ();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView mdevice;
CardView cardView;
public ViewHolder( View itemView) {
super (itemView);
mdevice = itemView.findViewById (R.id.device);
cardView = itemView.findViewById (R.id.mcardview);
}
}
}
答案 0 :(得分:0)
public interface ListOwner {
void push(ArrayList<String> list);
}
private ListOwner listOwner;
public MainAdapter(ArrayList<String> lista_shows, Context context, ListOwner owner) {
this.lista_show = lista_shows;
this.listOwner = owner;
}
if (listOwner != null) {
listOwner.push(list_add);
}
ListOwner
:public class MyActivity extends AppCompatActivity implements ListOwner {
// all code
// create instance of adapter:
mAdapter = new MainAdapter(list_show, MyActivity.this, MyActivity.this);
@Override
public void push(ArrayList<String> list) {
// you have the list here
}
}
PS
您可以省略界面并将引用直接传递给Activity
(示例中的MyActivity
)