我正在使用Android应用。
有一个活动有两个独立的回收者视图。
第一个是水平的,有自己的适配器。 第二个是垂直的,也有自己的适配器。
第一次启动活动时,两个回收站视图均显示其各自来源中的所有物品。
但是稍后我需要根据从第一个recyclerview中选择的项目过滤要显示在第二个recycler视图中的项目。
在第一个适配器上,单击某个项目时,我会从中获得ID,该ID可用于从第二个recyclerview中过滤这些项目。
哪种ID是将ID从第一个recyclerview单击的项目传递到第二个recyclerview的最佳方法,而无需重新加载活动?
这是我从第一个适配器获取ID的方法:
class MenuClickListener implements PopupMenu.OnMenuItemClickListener {
Integer pos;
public MenuClickListener(int pos) {
this.pos = pos;
}
@Override
public boolean onMenuItemClick(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.action_favourite:
String positi = marcaList.get(pos).getnombre();
Integer positid = marcaList.get(pos).getId();
return true;
default:
}
return false;
}
}
两个recyclerviews都是从远程数据库填充的。
编辑
片段代码
public class HomeFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener {
private static final String TAG = "MainActivity";
private static final String URL_PRODUCTS = "https://.../Api.php";
SwipeRefreshLayout mSwipeRefreshLayout;
//a list to store all the products
List<Marca> marcaList;
//the recyclerview
RecyclerView recyclerView;
RecyclerView recyclerView1;
public List<Dispositivo> dispositivos;
EditText cadenaNf,cadenaCf;
private GridLayoutManager gridLayout;
private DispositivoAdapter adapter;
private Button botonbuscar;
private String cadenaC,cadenaN;
private SearchView searchView = null;
private SearchView.OnQueryTextListener queryTextListener;
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// Do something that differs the Activity's menu here
super.onCreateOptionsMenu(menu, inflater);
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.home, container, false);
//getting the recyclerview from xml
recyclerView = v.findViewById(R.id.recyclerMarcas);
recyclerView.setHasFixedSize(true);
LinearLayoutManager layoutManager
= new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false);
recyclerView.setLayoutManager(layoutManager);
marcaList = new ArrayList<>();
loadProducts();
// SwipeRefreshLayout
mSwipeRefreshLayout = (SwipeRefreshLayout) v.findViewById(R.id.swipeRefreshLayout);
mSwipeRefreshLayout.setOnRefreshListener(this);
mSwipeRefreshLayout.setColorSchemeResources(R.color.colorPrimary,
android.R.color.holo_green_dark,
android.R.color.holo_orange_dark,
android.R.color.holo_blue_dark);
/**
* Showing Swipe Refresh animation on activity create
* As animation won't start on onCreate, post runnable is used
*/
mSwipeRefreshLayout.post(new Runnable() {
@Override
public void run() {
mSwipeRefreshLayout.setRefreshing(true);
// dispositivos.clear();
// Fetching data from server
// getDispositivosFromDB(0);
}
});
cadenaNf = (EditText) getActivity().findViewById(R.id.cadenaNtxt);
cadenaNf.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
Log.d("SEARCH string", "pulsado search ANTES DE ESCRIBIR CADENA N "+ charSequence);
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
Log.d("SEARCH string", "pulsado search ESCRIBIENDO CADENA N "+ charSequence);
if(charSequence.length() >3 ){
dispositivos.clear();
getDispositivosBusquedaFromDB(0, charSequence.toString());
}
if(charSequence.length()== 0 ){
dispositivos.clear();
getDispositivosFromDB(0);
}
Log.d("SEARCH string", "pulsado search submit N FFF CHANGE "+ charSequence);
}
@Override
public void afterTextChanged(Editable editable) {
dispositivos.clear();
Log.d("SEARCH string", "pulsado search submit N FFF "+editable );
Log.d("SEARCH string", "pulsado search ENVIADA CADENA N "+ editable);
}
});
cadenaCf = (EditText) getActivity().findViewById(R.id.cadenaCtxt);
cadenaCf.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
Log.d("SEARCH string", "pulsado search ANTES DE ESCRIBIR CADENA C "+ charSequence);
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
Log.d("SEARCH string", "pulsado search ESCRIBIENDO CADENA C "+ charSequence);
Log.d("SEARCH string", "pulsado search submit N FFF CHANGE "+ charSequence);
if(charSequence.length() >3 ){
dispositivos.clear();
getDispositivosBusquedaFromDB(0, charSequence.toString());
}
if(charSequence.length()== 0 ){
dispositivos.clear();
getDispositivosFromDB(0);
}
}
@Override
public void afterTextChanged(Editable editable) {
dispositivos.clear();
Log.d("SEARCH string", "pulsado search submit CCC FFF "+editable );
Log.d("SEARCH string", "pulsado search ENVIADA CADENA C "+ editable);
}
});
// getData();
recyclerView1 = (RecyclerView) v.findViewById(R.id.recyclerView1);
dispositivos = new ArrayList<>();
gridLayout = new GridLayoutManager(getActivity(), 2);
recyclerView1.setLayoutManager(gridLayout);
adapter = new DispositivoAdapter(getActivity(), dispositivos);
dispositivos.clear();
recyclerView1.setAdapter(adapter);
getDispositivosFromDB(0);
return v;
}
private void getDispositivosBusquedaFromDB(int id, final String busqueda) {
Log.d("HOLA ADDRESSES", "DIRECCION LEIDA ESTOY BUSCANDO: "+busqueda);
dispositivos.clear();
mSwipeRefreshLayout.setRefreshing(true);
Log.d("estoy en directorio= ",busqueda);
Log.d("Texto buscado= ",busqueda);
AsyncTask<Integer, Void, Void> asyncTask = new AsyncTask<Integer, Void, Void>() {
@Override
protected Void doInBackground(Integer... addressesIds) {
String URL = "https://._busca.php?id="+busqueda;
OkHttpClient client = new OkHttpClient();
okhttp3.Request request = new okhttp3.Request.Builder()
.url(URL)
.build();
try {
okhttp3.Response response = client.newCall(request).execute();
Log.d("Texto buscado=estoy ",busqueda);
JSONArray array = new JSONArray(response.body().string());
for (int i = 0; i < array.length(); i++) {
Log.d("Texto buscado loop= ",busqueda);
JSONObject object = array.getJSONObject(i);
Log.d("HOLA ADDRESSES", "DIRECCION LEIDA: " + i);
Dispositivo dispositivo = new Dispositivo(object.getInt("id_dispositivo"),
object.getString("usuario_dispositivo"),
object.getString("fecha_dispositivo"),
object.getString("precio_dispositivo"),
object.getString("garantia"),
object.getString("estado"),
object.getString("estado_publicacion"),
object.getString("localizacion"),
object.getString("comentarios"),
object.getString("modelo_dispositivo"),
object.getString("foto_dispositivo"),
object.getString("foto2"),
object.getString("foto3"),
object.getString("foto4"),
object.getString("foto5"),
object.getString("hora_dispositivo"),
object.getString("modelo_del_dispositivo"),
object.getString("logo_marca")
);
dispositivos.add(dispositivo);
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
recyclerView1.swapAdapter(adapter, true);
mSwipeRefreshLayout.setRefreshing(false);
}
};
asyncTask.execute(id);
}
private void getDispositivosFromDB(int id) {
Log.d("HOLA ADDRESSES", "DIRECCION LEIDA SIN BUSCAR: ");
dispositivos.clear();
mSwipeRefreshLayout.setRefreshing(true);
AsyncTask<Integer, Void, Void> asyncTask = new AsyncTask<Integer, Void, Void>() {
@Override
protected Void doInBackground(Integer... addressesIds) {
// Log.d("HOLA PERFIL", "UID REGISTRADO ANTES DE CARGAR REECYCLER: " + user_id);
// ********我需要从适配器1接收的ID //字符串ID =(从adapter1接收到的ID)
OkHttpClient client = new OkHttpClient();
okhttp3.Request request = new okhttp3.Request.Builder()
.url("...todos.php?id="+id)
.build();
try {
okhttp3.Response response = client.newCall(request).execute();
JSONArray array = new JSONArray(response.body().string());
for (int i = 0; i < array.length(); i++) {
JSONObject object = array.getJSONObject(i);
Log.d("HOLA ADDRESSES", "DIRECCION LEIDA busqueda: " + i);
Log.d("DISPOSITIVOS", "DISPOSITIVO: " + object);
Dispositivo dispositivo = new Dispositivo(object.getInt("id_dispositivo"),
object.getString("usuario_dispositivo"),
object.getString("fecha_dispositivo"),
object.getString("precio_dispositivo"),
object.getString("garantia"),
object.getString("estado"),
object.getString("estado_publicacion"),
object.getString("localizacion"),
object.getString("comentarios"),
object.getString("modelo_dispositivo"),
object.getString("foto_dispositivo"),
object.getString("foto2"),
object.getString("foto3"),
object.getString("foto4"),
object.getString("foto5"),
object.getString("hora_dispositivo"),
object.getString("modelo_del_dispositivo"),
object.getString("logo_marca")
);
dispositivos.add(dispositivo);
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
adapter.notifyDataSetChanged();
mSwipeRefreshLayout.setRefreshing(false);
}
};
asyncTask.execute(id);
}
private void loadProducts() {
/*
* Creating a String Request
* The request type is GET defined by first parameter
* The URL is defined in the second parameter
* Then we have a Response Listener and a Error Listener
* In response listener we will get the JSON response as a String
* */
StringRequest stringRequest = new StringRequest(Request.Method.GET, URL_PRODUCTS,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
//converting the string to json array object
JSONArray array = new JSONArray(response);
Log.d("HOLA PERFIL", "RESPONSE 2 valor=" + response);
//traversing through all the object
for (int i = 0; i < array.length(); i++) {
//getting product object from json array
JSONObject marca = array.getJSONObject(i);
//adding the product to product list
marcaList.add(new Marca(
marca.getInt("id"),
marca.getString("nombre"),
marca.getString("icono")
));
}
//creating adapter object and setting it to recyclerview
MarcasAdapter adapter = new MarcasAdapter(getActivity(), marcaList);
recyclerView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
//adding our stringrequest to queue
Volley.newRequestQueue(getActivity()).add(stringRequest);
}
@Override
public void onRefresh() {
dispositivos.clear();
getDispositivosFromDB(0);
}
public void onResume(){
super.onResume();
Log.d("HOLA PERFIL", "BUSCANDO ONCREATEA CCAA:ONRESUME ANTES DE CLEAR ");
Log.d("HOLA PERFIL", "BUSCANDO ONCREATEA CCAA:ONRESUME DESPUES DE CLEAR ");
// Set title bar
((MainActivity) getActivity())
.setActionBarTitle("Portada de Jogua");
}
}
适配器1代码MarcasAdapter
public class MarcasAdapter extends RecyclerView.Adapter<MarcasAdapter.ProductViewHolder> {
private Context mCtx;
private List<Marca> marcaList;
private SharedPreferences mPref;
public MarcasAdapter(Context mCtx, List<Marca> marcaList) {
this.mCtx = mCtx;
this.marcaList = marcaList;
}
@Override
public ProductViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(mCtx);
View view = inflater.inflate(R.layout.marcas_list, null);
return new ProductViewHolder(view);
}
@Override
public void onBindViewHolder(ProductViewHolder holder, int position) {
Marca marca = marcaList.get(position);
String url = "https://jogua.es/administrar/application/admin/iconos/";
//loading the image
Glide.with(mCtx)
.load(url+marca.geticono())
.into(holder.imageView);
}
@Override
public int getItemCount() {
return marcaList.size();
}
class ProductViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView textViewTitle;
ImageView imageView;
public ProductViewHolder(View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.imageView);
itemView.setOnClickListener(this);
}
@Override
public void onClick(View v) {
int position = getAdapterPosition();
showPopupMenu(v, position);
Log.d("HOLA PERFIL", "RESPONSE 2 valor=" + position);
}
private void showPopupMenu(View view, int poaition) {
PopupMenu popup = new PopupMenu(mCtx, view);
MenuInflater inflater = popup.getMenuInflater();
inflater.inflate(R.menu.menu_context_directorio, popup.getMenu());
popup.setOnMenuItemClickListener(new MenuClickListener(poaition));
popup.show();
}
class MenuClickListener implements PopupMenu.OnMenuItemClickListener {
Integer pos;
public MenuClickListener(int pos) {
this.pos = pos;
}
@Override
public boolean onMenuItemClick(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.action_favourite:
String positi = marcaList.get(pos).getnombre();
Integer positid = marcaList.get(pos).getId();
return true;
default:
}
return false;
}
}
}
}
适配器2代码DispositivosAdapter
import android.content.Context;
import android.content.SharedPreferences;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.mpidesarrollo.jogua.R;
import java.util.List;
import static android.content.Context.MODE_PRIVATE;
public class DispositivoAdapter extends RecyclerView.Adapter<DispositivoAdapter.ViewHolder> {
private Context context;
private List<Dispositivo> dispositivos;
private String emailsegundo;
private SharedPreferences mPref;
private static final String PREF_NAME = "dispositivo";
private static final String BACK_STACK_ROOT_TAG = "detalle_disp";
public DispositivoAdapter(Context context, List<Dispositivo> dispositivos) {
this.context = context;
this.dispositivos = dispositivos;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.dispositivo_card,parent,false);
return new ViewHolder(itemView);
}
@Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.txtnombre.setText(dispositivos.get(position).getmodelo_del_dispositivo());
String precio = dispositivos.get(position).getprecio_dispositivo().toString();
String newString = precio.replace(".", ",");
holder.txtPrecio.setText(newString+" €");
String url_foto = "https://jogua.es/administrar/application/admin/dispositivos/"+dispositivos.get(position).getfoto_dispositivo();
Glide.with(context).load(url_foto).into(holder.imageView);
String url_logoMarca = "https://jogua.es/administrar/application/admin/iconos/"+dispositivos.get(position).getlogo_marca();
Glide.with(context).load(url_logoMarca).into(holder.logoMarca);
}
@Override
public int getItemCount() {
return dispositivos.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public TextView txtnombre,txtPrecio;
public ImageView imageView;
public ImageView logoMarca;
public ViewHolder(View itemView) {
super(itemView);
txtnombre = (TextView) itemView.findViewById(R.id.txtnombre);
txtPrecio = (TextView) itemView.findViewById(R.id.txtprecio);
imageView = (ImageView) itemView.findViewById(R.id.foto);
logoMarca = (ImageView) itemView.findViewById(R.id.logoMarca);
itemView.setOnClickListener(this);
}
@Override
public void onClick(View v) {
int position = getAdapterPosition();
mPref = context.getSharedPreferences(PREF_NAME, MODE_PRIVATE);
SharedPreferences.Editor editor = mPref.edit();
Log.d("DISPOSITIVO", "dispositivo pulsado"+position );
editor.putInt("ID_DISPOSITIVO", dispositivos.get(position).getid_dispositivo());
editor.putString("FOTO_DISPOSITIVO", dispositivos.get(position).getfoto_dispositivo());
editor.putString("FOTO2", dispositivos.get(position).getfoto2());
editor.putString("FOTO3", dispositivos.get(position).getfoto3());
editor.putString("FOTO4", dispositivos.get(position).getfoto4());
editor.putString("FOTO5", dispositivos.get(position).getfoto5());
editor.apply();
DetalleDispositivoFragment firstFragment = new DetalleDispositivoFragment();
((MainActivity)context).getSupportFragmentManager().beginTransaction()
.addToBackStack(BACK_STACK_ROOT_TAG)
.replace(R.id.content_frame, firstFragment).commit();
//showPopupMenu(v,position);
}
}
}
答案 0 :(得分:1)
class MenuClickListener implements PopupMenu.OnMenuItemClickListener {
Integer pos;
public MenuClickListener(int pos) {
this.pos = pos;
}
@Override
public boolean onMenuItemClick(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.action_favourite:
String positi = marcaList.get(pos).getnombre();
Integer positid = marcaList.get(pos).getId();
// do network operation here
// Eg: arraylist = api.getMobile(positid);
// update vertical recyclerview's data here
// verticalAdapter = new VerticalAdapter(arraylist);
return true;
default:
}
return false;
}
}
答案 1 :(得分:1)
单击第一个回收者视图项目时,将相应的ID或信息传递给另一种方法(例如:setSecondRV(id OR information))。在此方法中,您可以进行网络操作或常规操作以获得所需的列表。然后通过将列表传递到第二个适配器来设置第二个回收者视图。 不要忘记通知适配器(secondAdapter.notifyDataSetChanged();)
这是新闻应用程序的链接,该应用程序根据单击的第一个回收者视图项目对第二个回收者视图进行网络操作。