Beginniqg

零基础,从记录开始

搜索功能

布局代码:


搜索到的布局:


写点本地数据:


完整代码:

public class MainActivity extends Activity {
private ListView listView;
private EditText editText;
private ArrayList<String> arrayListlist = new ArrayList<String>();
private String state;//设置国家变量


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.lv);
listView.setAdapter(new Adapter(MainActivity.this, arrayListlist));
// 循环插入数据
for (int i = 0; i < Cheeses.sStrings.length; i++) {
arrayListlist.add(Cheeses.sStrings[i]);
}
// 对于EditText里面输入的内容进行判断
editText = (EditText) findViewById(R.id.edt);
editText.addTextChangedListener(new TextWatcher() {


@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
if (editText.getText().toString() != null) {
state = editText.getText().toString();
search(state);
}
// selectorData(s.toString());


}


@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub


}


@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub


}
});
}


public void search(String string) {
arrayListlist.clear();
for (int i = 0; i < Cheeses.sStrings.length; i++) {
// if(TextUtils.isEmpty(str)){
// arrayListlist=new ArrayList<String>();
// }else
if (Cheeses.sStrings[i].contains(string)) {
arrayListlist.add(Cheeses.sStrings[i]);
}


}
// 只在当前的listview上进行搜索
listView.setAdapter(new Adapter(MainActivity.this, arrayListlist));


}






}




设置适配器:

public class Adapter extends BaseAdapter {
ArrayList<String> Data = null;
Context context;


public Adapter(Context context, List<String> list) {
this.context = context;
this.Data = (ArrayList<String>) list;
}


@Override
public int getCount() {
// TODO Auto-generated method stub


return Data == null ? 0 : Data.size();
}


@Override
public Object getItem(int position) {
return Data.get(position);
}


@Override
public long getItemId(int position) {
return position;
}


static class ViewHolder {
TextView mtv;
}


@Override
public View getView(int position, View convertview, ViewGroup parent) {
ViewHolder viewHolder;
if (convertview == null) {
viewHolder = new ViewHolder();
convertview = LayoutInflater.from(context).inflate(R.layout.item,
null);
viewHolder.mtv = (TextView) convertview.findViewById(R.id.tv);
convertview.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertview.getTag();


}


viewHolder.mtv.setText(Data.get(position).toString());


return convertview;
}


}

阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

搜索功能

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭