我一直在尝试使用list-view在操作栏中实现搜索视图。我
project包含一个带有自定义适配器的列表视图,该适配器由
扩展
阵列适配器。我从dataHelper类中获取数据。我有模型类,其中包含名称和电话字段。我如何使用名称过滤列表视图
MainActivity
private ActionBar actionBar;
private ListView listView;
DatabaseHelper databaseHelper;
ArrayList<Personinfo> list;
ArrayAdapter<Personinfo> arrayAdapter;
AdapterFilter adapterfilter;
Personinfo personinfo;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setBackgroundDrawable(new ColorDrawable(Color
.parseColor("#03A9F4")));
actionBar.setTitle("Agarwal Association");
list = new ArrayList<Personinfo>();
databaseHelper = new DatabaseHelper(this);
csvToSqlite();
listView = (ListView) findViewById(R.id.listView);
getlistData();
adapterfilter = new AdapterFilter(this, R.layout.child_listview, list);
// adapter = new ListAdapter(MainActivity.this, list);
Log.i("List", "" + list.get(0).getPhoneno());
listView.setAdapter(adapterfilter);
listView.setTextFilterEnabled(true);
synchronized (listView) {
listView.notify();
// }
}
// final TextView txtviewnumber = (TextView)
// findViewById(R.id.phoneno);
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Toast.makeText(getApplicationContext(),
((TextView) view).getText(), Toast.LENGTH_SHORT).show();
}
});
}
public void getlistData() {
// TODO Auto-generated method stub
Cursor cursor = databaseHelper.getData();
cursor.moveToFirst();
do {
String name = cursor.getString(cursor.getColumnIndex("Name"));
String phoneNo = cursor.getString(cursor.getColumnIndex("PhoneNo"));
Personinfo personinfo = new Personinfo(name, phoneNo);
list.add(personinfo);
} while (cursor.moveToNext());
cursor.close();
}
public void csvToSqlite() {
try {
String reader = "";
boolean skipheader = true;
InputStream inputStream = getResources().openRawResource(
R.raw.agrawalsurnamedata);
BufferedReader in = new BufferedReader(new InputStreamReader(
inputStream));
while ((reader = in.readLine()) != null) {
// skip header column name from csv
if (skipheader) {
skipheader = false;
continue;
}
String[] RowData = reader.split(",");
if (databaseHelper.insertContact(RowData) == true) {
Log.i("inside csvToSqlite()", " data inserted successfully");
} else {
Log.i("inside csvToSqlite()",
" data is not inserted into db");
}
}
in.close();
} catch (Exception e) {
e.getMessage();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) menu.findItem(R.id.action_search)
.getActionView();
searchView.setSearchableInfo(searchManager
.getSearchableInfo(getComponentName()));
SearchView.OnQueryTextListener textChangeListener = new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextChange(String newText) {
// this is your adapter that will be filtered
adapterfilter.getFilter().filter(newText);
return true;
}
@Override
public boolean onQueryTextSubmit(String query) {
adapterfilter.getFilter().filter(query);
return true;
}
};
searchView.setOnQueryTextListener(textChangeListener);
return super.onCreateOptionsMenu(menu);
}
}
AdapterFilter
public class AdapterFilter extends ArrayAdapter<Personinfo> {
ArrayList<Personinfo> list = new ArrayList<Personinfo>();
Context context;
LayoutInflater inflater;
public AdapterFilter(Context context, int resource,
ArrayList<Personinfo> list) {
super(context, resource);
this.list = list;
this.context = context;
inflater = LayoutInflater.from(this.context);
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
@Override
public Personinfo getItem(int position) {
// TODO Auto-generated method stub
return list.get(position);
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder viewHolder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.child_listview, parent,
false);
viewHolder = new ViewHolder(convertView);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
final Personinfo personinfo = (Personinfo) getItem(position);
viewHolder.txtName.setText(personinfo.getName());
viewHolder.txtPhone.setText(personinfo.getPhoneno());
viewHolder.imageButtonCalling.setOnClickListener(new OnClickListener() {
// Calling on selected number
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(context, "number button Clicked",
Toast.LENGTH_SHORT).show();
String selectedChildPhone = personinfo.getPhoneno();
String phoneNo = "tel:" + selectedChildPhone.trim();
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse(phoneNo));
context.startActivity(intent);
}
});
viewHolder.imageButtonMessage.setOnClickListener(new OnClickListener() {
// Sending sms to whatsapp
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(context, "meesaage button Clicked",
Toast.LENGTH_SHORT).show();
String selectedChildPhone = personinfo.getPhoneno();
Uri mUri = Uri.parse("smsto:" + selectedChildPhone);
Intent smsIntent = new Intent(
android.content.Intent.ACTION_SEND);
smsIntent.setType("text/plain");
smsIntent.putExtra("address", mUri);
smsIntent.putExtra("sms_body", "your desired message");
context.startActivity(smsIntent);
}
});
return convertView;
}
private class ViewHolder {
TextView txtName, txtPhone;
ImageButton imageButtonCalling, imageButtonMessage;
public ViewHolder(View item) {
txtName = (TextView) item.findViewById(R.id.person_name);
txtPhone = (TextView) item.findViewById(R.id.phoneno);
imageButtonCalling = (ImageButton) item
.findViewById(R.id.imageButtonCalling);
imageButtonMessage = (ImageButton) item
.findViewById(R.id.imageButtonMessage);
}
}
}
Personinfo.java
public class Personinfo {
private String name;
private String phoneno;
public Personinfo(String name, String phoneno) {
super();
this.name = name;
this.phoneno = phoneno;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhoneno() {
return phoneno;
}
public void setPhoneno(String phoneno) {
this.phoneno = phoneno;
}
}
我正在尝试,但listview没有按名称过滤。我的错误在哪里请建议我!!! 感谢
答案 0 :(得分:0)
在自定义适配器中实现getFilter()方法,根据搜索查询过滤列表视图。您必须为搜索功能实现Filterable接口
public class AdapterFilter extends ArrayAdapter<Personinfo> implements Filterable{
ArrayList<Personinfo> list = new ArrayList<Personinfo>();
Context context;
LayoutInflater inflater;
public ArrayList<Personinfo> orig;
public AdapterFilter(Context context, int resource,
ArrayList<Personinfo> list) {
super(context, resource);
this.list = list;
this.context = context;
inflater = LayoutInflater.from(this.context);
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
@Override
public Personinfo getItem(int position) {
// TODO Auto-generated method stub
return list.get(position);
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder viewHolder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.child_listview, parent,
false);
viewHolder = new ViewHolder(convertView);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
final Personinfo personinfo = (Personinfo) getItem(position);
viewHolder.txtName.setText(personinfo.getName());
viewHolder.txtPhone.setText(personinfo.getPhoneno());
viewHolder.imageButtonCalling.setOnClickListener(new OnClickListener() {
// Calling on selected number
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(context, "number button Clicked",
Toast.LENGTH_SHORT).show();
String selectedChildPhone = personinfo.getPhoneno();
String phoneNo = "tel:" + selectedChildPhone.trim();
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse(phoneNo));
context.startActivity(intent);
}
});
viewHolder.imageButtonMessage.setOnClickListener(new OnClickListener() {
// Sending sms to whatsapp
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(context, "meesaage button Clicked",
Toast.LENGTH_SHORT).show();
String selectedChildPhone = personinfo.getPhoneno();
Uri mUri = Uri.parse("smsto:" + selectedChildPhone);
Intent smsIntent = new Intent(
android.content.Intent.ACTION_SEND);
smsIntent.setType("text/plain");
smsIntent.putExtra("address", mUri);
smsIntent.putExtra("sms_body", "your desired message");
context.startActivity(smsIntent);
}
});
return convertView;
}
@Override
public Filter getFilter() {
return new Filter() {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
final FilterResults oReturn = new FilterResults();
final ArrayList<Personinfo> results = new ArrayList<Personinfo>();
if (orig == null) {
orig = list;
}
if (constraint != null) {
if (orig != null && orig.size() > 0) {
for (final Personinfo g : orig) {
if (g.getName().toLowerCase(Locale.getDefault()).contains(constraint.toString())) {
results.add(g);
}
}
}
oReturn.values = results;
} else {
oReturn.values = list;
}
return oReturn;
}
@SuppressWarnings("unchecked")
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
list = (ArrayList<Personinfo>) results.values;
notifyDataSetChanged();
}
};
}
private class ViewHolder {
TextView txtName, txtPhone;
ImageButton imageButtonCalling, imageButtonMessage;
public ViewHolder(View item) {
txtName = (TextView) item.findViewById(R.id.person_name);
txtPhone = (TextView) item.findViewById(R.id.phoneno);
imageButtonCalling = (ImageButton) item
.findViewById(R.id.imageButtonCalling);
imageButtonMessage = (ImageButton) item
.findViewById(R.id.imageButtonMessage);
}
}
}
我希望它有所帮助!
答案 1 :(得分:0)
这里是我的示例代码,希望对此有所帮助
public class MainActivity extends Activity implements
SearchView.OnQueryTextListener, SearchView.OnCloseListener {
...
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
...
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) findViewById(R.id.searchView);
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setIconifiedByDefault(true);
searchView.setOnQueryTextListener(this);
searchView.setOnCloseListener(this);
}
@Override
public boolean onClose() {
if (listAdapter != null) {
listAdapter.filterData("");
}
return false;
}
@Override
public boolean onQueryTextSubmit(String query) {
if (listAdapter != null) {
listAdapter.filterData(query);
}
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
if (listAdapter != null) {
listAdapter.filterData(newText);
}
return false;
}
}
public void filterData(String query) {
query = query.toLowerCase();
mList.clear();
if (query.isEmpty()) {
mList.addAll(mList_original);
} else {
for (String header : mList_original) {
if (header.toLowerCase().contains(query)) {
mList.add(header);
}
}
}
notifyDataSetChanged();
}