SearchView во фрагменте и OnClickListener - PullRequest
0 голосов
/ 26 июня 2019

Кликает одну запись и переходит на другую при использовании поиска.Я попытался изменить адаптер и framgmento, и мне не удалось.Кто-нибудь может мне помочь?Я полагаю, что проблема во фрагменте должна быть в (onQueryTextChange).

Ссылка на проект в github: https://github.com/vpsilvay/BD_Carros

Fragment


public class CarrosFragment extends BaseFragment implements SearchView.OnQueryTextListener{
protected RecyclerView recyclerView;
private List<Carro> carros;
private LinearLayoutManager linearLayoutManager;
private String tipo; //the type of carro that is received as an argument in the construction of the fragment
private CarroServiceBD carroServiceBD; //instance of access to bd

public CarrosFragment() {
    // Required empty public constructor
}

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);


// create bd if it is not yet created
    // or get the instance of access to bd
    carroServiceBD = CarroServiceBD.getInstance(getContext());

    //if there are arguments, stores it to filter the list of carros
    if (getArguments() != null) {
        this.tipo = getArguments().getString("tipo");
    }

    setHasOptionsMenu(true); //enable inflate menu in Fragment

    ((CarrosActivity) getActivity()).getSupportActionBar().setTitle(R.string.titulo_fragmentcarros);  //um título para a janela

    //if it is Android 6. + request permission to access the file system
    if(ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE)
            == android.content.pm.PackageManager.PERMISSION_GRANTED) {

    }else{

    }
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_carros, container, false);

    recyclerView = (RecyclerView) view.findViewById(R.id.recyclerview_fragmentcaroos); //maps to RecyclerView
    linearLayoutManager = new LinearLayoutManager(getActivity()); //build the layout manager
    recyclerView.setLayoutManager(linearLayoutManager); //add manager
    recyclerView.setItemAnimator(new DefaultItemAnimator()); //animation manager
    recyclerView.setHasFixedSize(true);

    //search the data in the database
    new Task().execute();

    return view;
}

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.menu_fragment_carros, menu); //inflates the menu

    //SearchView
    SearchView searchView = (SearchView) menu.findItem(R.id.menuitem_pesquisar).getActionView(); //maps SearchView
    searchView.setQueryHint(getString(R.string.hint_pesquisar)); //inserts a hint
    searchView.setOnQueryTextListener(this); //adds the attendant to the listener list
}

@Override
public boolean onQueryTextSubmit(String query) {
    //toast("When you press enter.");
    return true;
}

@Override
public boolean onQueryTextChange(String newText) {
    List<Carro> carroList = new ArrayList<>(); //a list for the new RecyclerView template layer

    for(Carro carro : carros){ //a for-eatch in the list of carros
        if(carro.nome.contains(newText)) { //if the car name contains the typed text
            carroList.add(carro); //add the car to the new list
        }
    }

    //Context, data source, event handler onClick
    recyclerView.setAdapter(new CarrosAdapter(getContext(), carroList, onClickCarro()));

    return true;
}

/*
    This method uses the interface declared in the CarrosAdapter class to handle the onClick event of the list item
 */
protected CarrosAdapter.CarroOnClickListener onClickCarro() {
    //invokes the interface (implicit) counter to create an instance of the interface declared on the adapter.
    return new CarrosAdapter.CarroOnClickListener() {
        // Here is the onItemClick event.
        @Override
        public void onClickCarro(View view, int idx) {
            //stores the car that was clicked
            Carro carro = carros.get(idx);
            //calls another Activity to drill down or edit the car clicked by user
            Intent intent = new Intent(getContext(), CarroActivity.class); //configures an explicit Intent
            intent.putExtra("carro", carro); //I inserted an extra with the reference to the carro object
            intent.putExtra("qualFragmentAbrir", "CarroDetalheFragment");
            startActivity(intent);
        }
    };
}

/*
    Internal class for asynchronous operations in the database.
 */
private class Task extends AsyncTask<Void, Void, List<Carro>>{ //<Params, Progress, Result>

    List<Carro> carros;

    @Override
    protected List<Carro> doInBackground(Void... voids) {
        //search the cars in the background, in an exclusive thread for this task.
        if(CarrosFragment.this.tipo.equals(getString(R.string.tabs_classicos))){
            return carroServiceBD.getByTipo(getString(R.string.tabs_classicos));
        }else if(CarrosFragment.this.tipo.equals(getString(R.string.tabs_esportivos))) {
            return carroServiceBD.getByTipo(getString(R.string.tabs_esportivos));
        }if(CarrosFragment.this.tipo.equals(getString(R.string.tabs_luxo))){
            return carroServiceBD.getByTipo(getString(R.string.tabs_luxo));
        }else if(CarrosFragment.this.tipo.equals(getString(R.string.tabs_todos))) {
            return carroServiceBD.getAll();
        }

        return null;
    }

    @Override
    protected void onPostExecute(List<Carro> carros) {
        super.onPostExecute(carros);
        //copy the list of cars for use on onQueryTextChange ()
        CarrosFragment.this.carros = carros;
        //update the view in UIThread
        recyclerView.setAdapter(new CarrosAdapter(getContext(), carros, onClickCarro())); //Context, fonte de dados, tratador do evento onClick
    }
}}//finner class end

OnClick не получает правильное значение, когда используется представление поиска.

Adapter

public class CarrosAdapter extends RecyclerView.Adapter<CarrosAdapter.CarrosViewHolder> {
protected static final String TAG = "CarrosAdapter";
private final List<Carro> carros;
private final Context context;

private CarroOnClickListener carroOnClickListener;

public CarrosAdapter(Context context, List<Carro> carros, CarroOnClickListener carroOnClickListener) {
    this.context = context;
    this.carros = carros;
    this.carroOnClickListener = carroOnClickListener;
}

@Override
public int getItemCount() {
    return this.carros != null ? this.carros.size() : 0;
}

@Override
public CarrosViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
    // Inflates the view of the layout
    View view = LayoutInflater.from(context).inflate(R.layout.adapter_carros, viewGroup, false);

    // Creates ViewHolder
    CarrosViewHolder holder = new CarrosViewHolder(view);
    return holder;
}

@Override
public void onBindViewHolder(final CarrosViewHolder holder, final int position) {
    // Update the view
    Carro c = carros.get(position);
    Log.d(TAG, "Carro no Adapter da RecyclerView: " + c.toString());

    Log.d(TAG, c.toString());

    holder.tNome.setText(c.nome);
    holder.progress.setVisibility(View.VISIBLE);
    if(c.urlFoto != null){
        holder.img.setImageURI(Uri.parse(c.urlFoto));
    }else{
        holder.img.setImageResource(R.drawable.car_background);
    }

    // Click
    if (carroOnClickListener != null) {
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                carroOnClickListener.onClickCarro(holder.itemView, position); //The position variable is final
            }
        });
    }

    holder.progress.setVisibility(View.INVISIBLE);
}

public interface CarroOnClickListener {
    public void onClickCarro(View view, int idx);
}

// ViewHolder with views
public static class CarrosViewHolder extends RecyclerView.ViewHolder {
    public TextView tNome;
    ImageView img;
    ProgressBar progress;

    public CarrosViewHolder(View view) {
        super(view);
        // Cria views para salvar em ViewHolder
        tNome = (TextView) view.findViewById(R.id.textView_card_adaptercarro);
        img = (ImageView) view.findViewById(R.id.imageView_card_adaptercarro);
        progress = (ProgressBar) view.findViewById(R.id.progressBar_card_adaptercarro);
    }
}}
...