我想实现一个单击ListActivity中的Item弹出一个AlertDialog,Dialog的View中是一个AutoCompleteTextView,绑定了一个
ArrayAdapter,但是加上这一句就报错 actvTest.addTextChangedListener(this);,大家帮我看看是啥原因?
Main.java
- Java code
package net.blogjava.mobile; import java.util.HashMap; import java.util.List; import java.util.Map; import android.app.AlertDialog; import android.app.ListActivity; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.view.View; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; import android.widget.ListView; import android.widget.SimpleAdapter; public class Main extends ListActivity implements TextWatcher { private ArrayAdapter<String> adapter; private AutoCompleteTextView actvTest; private static String[] MainItems = new String[] {"线路查询","站点查询","站站查询"}; private String[] items = new String[] {"1","12","123","1234","12345"}; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); actvTest = (AutoCompleteTextView)findViewById(R.id.actvQuery); actvTest.addTextChangedListener(this); [color=#FF0000]//加上这一句就错,WHY?[/color] List<Map<String,String>> appItems = new ArrayList<Map<String,String>>(); for(int i=0;i<MainItems.length;i++) { Map<String,String> item = new HashMap<String,String>(); item.put("itemname", MainItems[i]); appItems.add(item); } SimpleAdapter simpleAdapter = new SimpleAdapter(this,appItems,R.layout.main, new String[]{"itemname"},new int[]{R.id.tvMainItem}); setListAdapter(simpleAdapter); } @Override protected void onListItemClick(ListView l, View v, int position, long id) { View testView = getLayoutInflater().inflate(R.layout.autocomplete, null); new AlertDialog.Builder(this).setTitle("查询").setMessage("自动完成提示") .setView(testView).setPositiveButton("确定", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }) .setNegativeButton("取消", null).show(); } @Override public void afterTextChanged(Editable s) { /*String sql = "select BUSNUM as _id from businfo where BUSNUM like ?"; Cursor cursor = database.rawQuery(sql, new String[] {s.toString()+"%"}); TestAdapter testAdapter = new TestAdapter(this,cursor,true); actvTest.setAdapter(testAdapter);*/ adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, items); actvTest.setAdapter(adapter); } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // TODO Auto-generated method stub } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // TODO Auto-generated method stub } }
------解决方案--------------------
很明显,你的两个布局文件不一样,不在一起,在findbyid前又没指定是哪个layout文件的context,默认就是this,this就是当前的上下文而在之前你有没有setContentView指定布局文件。所以空指针,是找不到AutoCompleteTextView的id。。不过貌似你的思路也有问题。。据说listview里是不能嵌套listview的。。你这里情况和这好像类似。具体我也没试过。等你效果了。。