我的Android应用程序包含一个带有图像的gridview和它下面的文本。我将一系列字符串传递给textview。我希望edittext字段充当搜索栏并过滤结果。我已经看到了与此相关的其他问题,但它们似乎过滤了传递给Listview的arraylist。如何在gridview中过滤字符串数组?
我知道我应该添加一个TextWatcher来监听EditText上的文本更改,但之后如何过滤我的数据?
这是我的代码
Mainactivity.java
public class MainActivity extends Activity {
EditText inputSearch;
GridView grid;
public static String[] Sname = {
"one",
"two",
"three",
"four",
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final CustomGrid adapter = new CustomGrid(MainActivity.this, Sname);
grid = (GridView) findViewById(R.id.grid);
grid.setAdapter(adapter);
grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(MainActivity.this, "You Clicked at " + Sname[+position], Toast.LENGTH_SHORT).show();
}
});
inputSearch = (EditText) findViewById(R.id.editText);
}
}
CustomGrid.java
public class CustomGrid extends BaseAdapter {
private Context mContext;
private final String[] Sname;
public CustomGrid(Context c,String[] Sname) {
mContext = c;
this.Sname = Sname;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return Sname.length;
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
@Override
public View getView(int position, View view, ViewGroup parent) {
// TODO Auto-generated method stub
View grid;
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
grid = new View(mContext);
grid = inflater.inflate(R.layout.grid_single, null);
TextView textView = (TextView) grid.findViewById(R.id.grid_text);
ImageView imageView = (ImageView)grid.findViewById(R.id.grid_image);
textView.setText(Sname[position]);
imageView.setImageResource(R.mipmap.image1);
return grid; }}
答案 0 :(得分:0)
您可以添加适配器,即CustomGrid
filter(String)
方法。
您还可以在适配器中添加字段String [] toDisplay
。
在您的构造函数中添加toDisplay = Sname
,并在所有其他方法中将Sname
替换为toDisplay
在filter
方法中创建一个新的字符串数组,其中只包含Sname
中与所需字符串匹配的字符串。将此新数组设置为toDisplay
。
然后在notifyDataSetChanged
CustomGrid
方法
过滤方法示例:
public void filter(String toMatch) {
List<String> matches = new ArrayList<String>();
for (String string : Sname) {
if (string.matches(toMatch)) {//on whatever mathcing you feel to use
matches.add(string);
}
}
toDisplay = new String[matches.size()];
toDisplay = matches.toArray(toDisplay);
notifyDataSetChanged(); //update your grid view
}