【发布时间】:2014-06-20 08:57:30
【问题描述】:
我在 MainActiviy 上有一个 EditText 和 ListView。 EditText 用于搜索和过滤 ListView 的项目。
我有两个数组;
newspapers[ ] 包含一些报纸名称,
adress[ ] 保存报纸的网址。
我还有一个setOnItemClickListener。在侦听器中,我得到了项目的位置,并借助这个数组的索引号从adress[ ] 数组中获取地址信息。
首先没有过滤器的搜索框。我将addTextChangedListener 添加到EditText 以过滤ListView 的项目。问题从这里开始!
当我向搜索框写入内容时,它会正确过滤,但过滤后如果我点击任何项目,它会打开旧项目的地址。
例子:
假设,
一个
B
C
D
是过滤器之前的项,A项在数组中的位置是0,B=1,C=2,D=3
如果我写搜索“C”,过滤后只有 C 可见,如果我单击“C”项,它会打开 A 的网站。因为“A”项是过滤前的第一项。
过滤ListView后如何更新数组索引位置?
public class MainActivity extends Activity {
// Search EditText
EditText inputSearch;
// Listview Adapter
ArrayAdapter<String> adapter;
protected static final String SITE_ADDRESS = null;
// protected static final String SITE_NAME = null;
private ListView newspaper_list_view;
private String[] newspapers = { "A","B","C","D" };
private String[] adress = { "a.com","b.com","c.com","d.com" };
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// setContentView(R.layout.webview);
inputSearch = (EditText) findViewById(R.id.inputSearch);
newspaper_list_view = (ListView) findViewById(R.id.gazeteliste);
adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, newspapers);
newspaper_list_view.setAdapter(adapter);
final Intent intent = new Intent(this, GazeteIcerik.class);
newspaper_list_view.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1,
int listposition, long arg3) {
// Toast.makeText(getApplicationContext(),"Liste Sırası:" +
// listposition, Toast.LENGTH_SHORT).show();
String site_adress = adress[listposition];
String site_name = newspapers[listposition];
intent.putExtra(SITE_ADDRESS, site_adress);
// intent.putExtra(SITE_NAME, site_name);
getActionBar().setDisplayHomeAsUpEnabled(true);
intent.putExtra(SITE_ADDRESS, new String[] { site_adress,site_name });
startActivity(intent);
}
});
inputSearch.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence cs, int arg1, int arg2,int arg3) {
// When user changed the Text
MainActivity.this.adapter.getFilter().filter(cs);
}
@Override
public void beforeTextChanged(CharSequence arg0, int arg1,int arg2, int arg3) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
}
// onCreate sonu
}
【问题讨论】:
标签: android arrays listview android-listview filter