gpt4 book ai didi

java - 如何使用搜索 View 而不一直显示回收器 View ?

转载 作者:行者123 更新时间:2023-12-02 09:36:19 26 4
gpt4 key购买 nike

我有一个 Activity ,其中有一些与此无关的按钮,以及顶部的相对布局内的搜索 View 。我想要的是,当我在 searchview 上写字时,recyclerview 数组出现在屏幕上,但是当我没有写任何内容时,只会出现我之前告诉过你的按钮。

为了避免在不使用 searchview 时显示 recyclerView,我所做的就是在其宽度和高度参数中设置 0dp。

这是我的 MainActivity.java:

public class Dishes extends AppCompatActivity implements Adaptador2.OnRecipeListener {
Button boton_verdura;
Button boton_carne;
Button boton_pasta;
Button boton_sopas;
Button boton_pescados;
Button boton_ensaladas;
private RecyclerView recyclerView;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dishes);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

boton_verdura=(Button) findViewById(R.id.boton_verduras);
boton_carne=(Button) findViewById(R.id.boton_carnes);
boton_pasta=(Button) findViewById(R.id.boton_pasta);
boton_sopas=(Button) findViewById(R.id.boton_sopas);
boton_pescados=(Button) findViewById(R.id.boton_pescados);
boton_ensaladas=(Button) findViewById(R.id.boton_ensaladas);

boton_verdura.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

Intent in = new Intent(Dishes.this,Verduras.class);
startActivity(in);
}
});

boton_carne.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

Intent in = new Intent(Dishes.this,Carnes.class);
startActivity(in);
}
});

boton_pasta.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

Intent in = new Intent(Dishes.this,Pasta.class);
startActivity(in);
}
});

boton_sopas.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

Intent in = new Intent(Dishes.this,Sopas.class);
startActivity(in);
}
});

boton_pescados.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

Intent in = new Intent(Dishes.this,Pescados.class);
startActivity(in);
}
});

boton_ensaladas.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

Intent in = new Intent(Dishes.this,Ensaladas.class);
startActivity(in);
}
});


recyclerView = findViewById(R.id.lv_prueba);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);

recyclerView.setLayoutManager(layoutManager);

List<Entidad2> listItems = new ArrayList<>();
listItems.add(new Entidad2(R.drawable.calabacines_3, "Calabacines", " 10 min.", 4, R.drawable.color_ensaladas));
listItems.add(new Entidad2(R.drawable.patatas_deluxe_especiadas_70523_300_150, "Patatas", " 15 min.", 2, R.drawable.color_ensaladas));
listItems.add(new Entidad2(R.drawable.tomate, "Tomates", " 2 min.", 5, R.drawable.color_ensaladas));

Adaptador2 Adaptador2 = new Adaptador2(listItems, this);
recyclerView.setAdapter(Adaptador2);
Adaptador2.notifyDataSetChanged();
}

@Override
public void OnRecipe(int position) {

if(position == 0){
Intent in = new Intent(this, Judias_verdes.class);
startActivity(in);
}
if(position == 1){
Intent in = new Intent(this, Sardinas_fritas.class);
startActivity(in);
}
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.example_menu, menu);

MenuItem searchItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) searchItem.getActionView();

searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
return false;
}

@Override
public boolean onQueryTextChange(String newText) {
Adaptador2.getFilter().filter(newText);
return false;
}
});
return true;
}
}

这是我的 Mainactivity.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffff00"
tools:context=".Dishes">

<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<RelativeLayout
android:layout_width="match_parent"
android:layout_height="84dp">

<android.support.v7.widget.SearchView
android:id="@+id/rv_buscar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="35dp"
android:layout_marginRight="35dp"
android:background="@drawable/line"
android:layout_centerVertical="true"
android:gravity="center_vertical">

</android.support.v7.widget.SearchView>

</RelativeLayout>

<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content">

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">

<Button
android:id="@+id/boton_sopas"
android:layout_width="match_parent"
android:layout_height="80dp"
android:layout_marginLeft="35dp"
android:layout_marginRight="35dp"
android:layout_weight="1"
android:background="@drawable/boton_redondo"
android:drawableLeft="@drawable/logo_sopa_15"
android:drawableStart="@drawable/logo_sopa_15"
android:text=" Sopas"
android:textAllCaps="false"
android:textSize="40sp"
android:textStyle="normal"
android:textAlignment="textStart"
android:layout_gravity="start"
app:fontFamily="@font/san_francisco_display_regular"
tools:ignore="HardcodedText,MissingConstraints"/>

<Button
android:id="@+id/boton_pescados"
android:layout_width="match_parent"
android:layout_height="80dp"
android:layout_marginLeft="35dp"
android:layout_marginRight="35dp"
android:layout_weight="1"
android:layout_marginTop="24dp"
android:background="@drawable/boton_redondo"
android:drawableLeft="@drawable/logo_pescado3_30_15"
android:drawableStart="@drawable/logo_pescado3_30_15"
android:text=" Pescados"
android:textAllCaps="false"
android:textSize="40sp"
android:textStyle="normal"
android:textAlignment="textStart"
android:layout_gravity="start"
app:fontFamily="@font/san_francisco_display_regular"
tools:ignore="HardcodedText,MissingConstraints" />

<Button
android:id="@+id/boton_ensaladas"
android:layout_width="match_parent"
android:layout_height="80dp"
android:layout_marginLeft="35dp"
android:layout_marginRight="35dp"
android:layout_weight="1"
android:layout_marginTop="24dp"
android:background="@drawable/boton_redondo"
android:drawableLeft="@drawable/logo_ensalada3_30_15"
android:drawableStart="@drawable/logo_ensalada3_30_15"
android:text=" Ensaladas"
android:textAllCaps="false"
android:textSize="40sp"
android:textStyle="normal"
android:textAlignment="textStart"
android:layout_gravity="start"
app:fontFamily="@font/san_francisco_display_regular"
tools:ignore="HardcodedText,MissingConstraints" />

<Button
android:id="@+id/boton_carnes"
android:layout_width="match_parent"
android:layout_height="80dp"
android:layout_marginLeft="35dp"
android:layout_marginRight="35dp"
android:layout_weight="1"
android:layout_marginTop="24dp"
android:background="@drawable/boton_redondo"
android:drawableLeft="@drawable/logo_filete_30_15"
android:drawableStart="@drawable/logo_filete_30_15"
android:text=" Carnes"
android:textAllCaps="false"
android:textSize="40sp"
android:textStyle="normal"
android:textAlignment="textStart"
android:layout_gravity="start"
app:fontFamily="@font/san_francisco_display_regular"
tools:ignore="DuplicateIds,HardcodedText,MissingConstraints" />

<Button
android:id="@+id/boton_verduras"
android:layout_width="match_parent"
android:layout_height="80dp"
android:layout_marginLeft="35dp"
android:layout_marginRight="35dp"
android:layout_weight="1"
android:layout_marginTop="24dp"
android:background="@drawable/boton_redondo"
android:drawableLeft="@drawable/logo_vegetables_30_15"
android:drawableStart="@drawable/logo_vegetables_30_15"
android:text=" Verduras"
android:textAllCaps="false"
android:textSize="40sp"
android:textStyle="normal"
android:textAlignment="textStart"
android:layout_gravity="start"
app:fontFamily="@font/san_francisco_display_regular"
tools:ignore="HardcodedText,MissingConstraints" />

<Button
android:id="@+id/boton_pasta"
android:layout_width="match_parent"
android:layout_height="80dp"
android:layout_marginBottom="15dp"
android:layout_marginLeft="35dp"
android:layout_marginRight="35dp"
android:layout_weight="1"
android:layout_marginTop="24dp"
android:background="@drawable/boton_redondo"
android:drawableLeft="@drawable/logo_pizza_30_15"
android:drawableStart="@drawable/logo_pizza_30_15"
android:text=" Pasta"
android:textAllCaps="false"
android:textSize="40sp"
android:textStyle="normal"
android:textAlignment="textStart"
android:layout_gravity="start"
android:fontFamily="@font/san_francisco_display_regular"
tools:ignore="HardcodedText,MissingConstraints" />

</LinearLayout>
</ScrollView>

<android.support.v7.widget.RecyclerView
android:id="@+id/lv_prueba"
android:layout_width="0dp"
android:layout_height="0dp">
</android.support.v7.widget.RecyclerView>

</LinearLayout>
</RelativeLayout>

这就是Adapter.java:

ackage com.test.platos_4;

import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

public class Adaptador2 extends RecyclerView.Adapter<Adaptador2.ViewHolder> implements Filterable
{
private List<Entidad2> listItems;
private List<Entidad2> listItemsFull;
private OnRecipeListener mOnRecipeListener;

public Adaptador2(List<Entidad2> listItems, OnRecipeListener onRecipeListener) {
this.listItems = listItems;
listItemsFull = new ArrayList<>(listItems);
this.mOnRecipeListener = onRecipeListener;
}


@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.elemento_lista2, parent, false);
return new ViewHolder(view, mOnRecipeListener);
}

@Override
public void onBindViewHolder(ViewHolder viewholder, int position) {
int resource = listItems.get(position).getImgFoto();
String title = listItems.get(position).getTitulo();
String time = listItems.get(position).getTiempo();
int barra = listItems.get(position).getRating();
final int priority = listItems.get(position).getPriority();
//int fondo = listItems.get(position).getColorfondo();
viewholder.setData(resource, title, time, barra);

//You can pass the clicked item's priority back to your activity like this
viewholder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mOnRecipeListener.OnRecipe(priority);
}
});
// por si necesito color de fondo viewholder.setData(resource, title, time, barra, fondo);
}

@Override
public int getItemCount() {
return listItems.size();
}

@Override
public Filter getFilter() {
return exampleFilter;
}

private Filter exampleFilter = new Filter() {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
List<Entidad2> filteredList = new ArrayList<>();

if (constraint == null || constraint.length() == 0) {
filteredList.addAll(listItemsFull);
}
else {
String filterPattern = constraint.toString().toLowerCase().trim();

for (Entidad2 item : listItemsFull) {
if (item.getTitulo().toLowerCase().contains(filterPattern)) {
filteredList.add(item);
}
}
}

FilterResults results = new FilterResults();
results.values = filteredList;

return results;
}

@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
listItems.clear();
listItems.addAll((List)results.values);
notifyDataSetChanged();
}
};

class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

private ImageView imgFoto;
private TextView titulo;
private TextView tiempo;
private RatingBar ratingBar;
//private ImageView colorfondo;
OnRecipeListener onRecipeListener;

public ViewHolder(View itemView, OnRecipeListener onRecipeListener) {
super(itemView);

imgFoto = itemView.findViewById(R.id.imgFoto);
titulo = itemView.findViewById(R.id.tvTitulo);
tiempo = itemView.findViewById(R.id.tvTiempo);
ratingBar = itemView.findViewById(R.id.ratingBarVerd);
//colorfondo = itemView.findViewById(R.id.colorfondo);
// this.onRecipeListener = onRecipeListener;

}

//por si necesito color de fondo private void setData(int resource, String title, String time, int barra, int fondo){
private void setData(int resource, String title, String time, int barra){
imgFoto.setImageResource(resource);
titulo.setText(title);
tiempo.setText(time);
ratingBar.setRating(barra);
//colorfondo.setImageResource(fondo);

}

@Override
public void onClick(View v) {
}
}

public interface OnRecipeListener{
void OnRecipe(int priority);
}
}

但是出现错误: enter image description here

请帮助我不知道该怎么做,因为我从未使用过 SearchView,所以任何帮助都会有用。

谢谢

当我尝试在运行应用程序时进入 Activity 时出现的新问题:

08-14 16:33:07.115 17470-17470/com.test.platos_4 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.test.platos_4, PID: 17470
java.lang.ClassCastException: android.support.v7.widget.SearchView cannot be cast to android.widget.SearchView
at com.test.platos_4.Dishes.onCreateOptionsMenu(Dishes.java:136)
at android.app.Activity.onCreatePanelMenu(Activity.java:3546)
at android.support.v4.app.FragmentActivity.onCreatePanelMenu(FragmentActivity.java:328)
at android.support.v7.view.WindowCallbackWrapper.onCreatePanelMenu(WindowCallbackWrapper.java:93)
at android.support.v7.app.AppCompatDelegateImplBase$AppCompatWindowCallbackBase.onCreatePanelMenu(AppCompatDelegateImplBase.java:332)
at android.support.v7.app.AppCompatDelegateImplV9.preparePanel(AppCompatDelegateImplV9.java:1370)
at android.support.v7.app.AppCompatDelegateImplV9.doInvalidatePanelMenu(AppCompatDelegateImplV9.java:1650)
at android.support.v7.app.AppCompatDelegateImplV9$1.run(AppCompatDelegateImplV9.java:134)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:201)
at android.app.ActivityThread.main(ActivityThread.java:6815)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)
08-14 16:33:07.119 17470-17470/com.test.platos_4 E/MQSEventManagerDelegate: failed to get MQSService.

最佳答案

您看到的 getFilter() 错误是因为您尝试在 Adaptador2 上调用 getFilter(),但由于 getFilter() 不是不是静态方法,您需要在适配器实例上调用它,而不是像 someInstanceOfAdapterClass.getFilter()

这样的适配器类

一个主要问题是您将适配器类实例命名为与类相同的名称,这是一个非常糟糕的主意......在这里:

Adaptador2 Adaptador2 = new Adaptador2(listItems, this); // this is bad
recyclerView.setAdapter(Adaptador2);
Adaptador2.notifyDataSetChanged();

如果您想将变量重命名为与类名不同的名称,常见的做法是使用小写字母。您还需要在 Activity 变量中跟踪它,以便可以在 onCreateOptionsMenu 中访问它,因此请执行以下操作:

// at the top of your main activity define it
private Adaptador2 adaptador2;
// create your instance of it 
adaptador2 = new Adaptador2(listItems, this);
recyclerView.setAdapter(adaptador2);
adaptador2.notifyDataSetChanged();
// in onCreateOptionsMenu use lower case one to reference the object instance not 
// the class
adaptador2.getFilter().filter(newText);
<小时/>

(我还没有测试过,但它可能有效)

至于隐藏回收器 View ,您可以在 onQueryChanged 方法中执行以下操作:

@Override
public boolean onQueryTextChange(String newText) {
// this will hide your recycler anytime the search query is empty
// and show it anytime there is a search query
if (newText == "") {
recyclerView.setVisibilty(View.GONE);
} else {
recyclerView.setVisibilty(View.VISIBLE);
}

adaptador2.getFilter().filter(newText);
return false;
}

关于java - 如何使用搜索 View 而不一直显示回收器 View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57480562/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com