问题代码如下:
public class WikiSuggestActivity extends Activity {
public String data;
public List suggest;
public AutoCompleteTextView autoComplete;
public ArrayAdapter aAdapter;
private static final String TAG = "WikiSuggestActivity";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
suggest = new ArrayList();
autoComplete = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView1);
autoComplete.setOnItemClickListener(itemClickListener);
autoComplete.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable editable) {
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
String newText = s.toString();
new getJson().execute(newText);
}
});
}
OnItemClickListener itemClickListener = new OnItemClickListener() {
@Override
public void onItemClick(AdapterView> parent, View view, int position,
long id) {
int key = parent.getId();
Log.d(TAG, "key is " + key + " and R.id.autoCompleteTextView1 is "
+ R.id.autoCompleteTextView1);
switch (key) {
case R.id.autoCompleteTextView1:
Log.d(TAG, "I am magic in place!");
break;
}
}
};
class getJson extends AsyncTask {
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
aAdapter = new ArrayAdapter(getApplicationContext(),
android.R.layout.simple_dropdown_item_1line, suggest);
autoComplete.setAdapter(aAdapter);
aAdapter.notifyDataSetChanged();
}
@Override
protected String doInBackground(String... key) {
String newText = key[0];
newText = newText.trim();
newText = newText.replace(" ", "+");
try {
HttpClient hClient = new DefaultHttpClient();
HttpGet hGet = new HttpGet(
"/w/api.php?action=opensearch&search="
+ newText + "&limit=8&namespace=0&format=json");
ResponseHandler rHandler = new BasicResponseHandler();
data = hClient.execute(hGet, rHandler);
suggest = new ArrayList();
JSONArray jArray = new JSONArray(data);
for (int i = 0; i < jArray.getJSONArray(1).length(); i++) {
String SuggestKey = jArray.getJSONArray(1).getString(i);
suggest.add(SuggestKey);
}
} catch (Exception e) {
Log.w("Error", e.getMessage());
}
return null;
}
}
}
解决方案:
编写simple_dropdown_item_1line.xml文件
android:id="@+id/text1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:ellipsize="marquee"
android:gravity="left"
android:paddingBottom="5dip"
android:paddingTop="5dip"
android:singleLine="true"
android:textColor="#ff000000"
android:textSize="22sp" />
修改Java代码
aAdapter = new ArrayAdapter(getApplicationContext(),
android.R.layout.simple_dropdown_item_1line, suggest);为:
aAdapter = new ArrayAdapter(getApplicationContext(),
R.layout.simple_dropdown_item_1line, suggest);