我正在嘗試自定義對話框。它應該從數據庫獲取字符串並填充一個列表。 我的對話:Android:使用列表創建自定義對話框
public class CountriesDialog extends AlertDialog {
private Context context;
private Vector<String> countries;
private ListView listView;
private CountriesAdapter adapter;
public CountriesDialog(Context context, Vector<String> countries) {
super(context);
this.context = context;
this.countries = countries;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
listView = new ListView(context);
listView.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT, 1.0f));
listView.setId(android.R.id.list);
Log.e("WORKS", " "+(listView == null) + " asas");
adapter = new CountriesAdapter(context, countries);
listView.setAdapter(adapter);
listView.setOnItemClickListener(adapter);
setInverseBackgroundForced(true);
setView(listView);
setTitle("Select country");
super.onCreate(savedInstanceState);
}
}
我的適配器(以自定義每個行):
public class CountriesAdapter extends ArrayAdapter<String> implements OnItemClickListener {
private Vector<String> countries;
private Context context;
public CountriesAdapter(Context context, Vector<String> countries) {
super(context, R.layout.countries_row);
this.context = context;
this.countries = countries;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.countries_row, parent, false);
ImageView imageView = (ImageView) rowView.findViewById(R.id.countries_list_single_image);
TextView textView = (TextView) rowView.findViewById(R.id.countries_list_single_text);
textView.setText(countries.get(position));
DatabaseManager db = new DatabaseManager(context);
db.connectForReading();
String recource = db.getFLagName(countries.get(position));
db.disconnect();
int resId = context.getResources().getIdentifier(recource, "drawable", "com.emaborsa");
imageView.setImageDrawable(context.getResources().getDrawable(resId));
Log.e("WORKS", recource);
return rowView;
}
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
}
}
應用程序不拋出任何異常。該對話框顯示...但空。我只看到標題和沒有行條目。 我做了一些嘗試,使用Log.e爲了查看代碼是否運行。從不調用適配器的getView,該對話框的onCreate是。 我認爲這個問題是在我的對話框的下面兩個行,但我不知道如何解決它:
listView.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT, 1.0f));
listView.setId(android.R.id.list);
你可能是對的。你使用的是什麼佈局參數,因爲它看起來像是用線性佈局的,而你正在處理的視圖是一個列表視圖。 – skUDA 2012-07-13 20:03:51
好吧,我明白了,但我不知道如何解決它。你能幫我多一點嗎? – Emaborsa 2012-07-13 20:08:01
看一看[listview api](http://developer.android.com/reference/android/widget/ListView.html)。你需要使用ViewGroup.LayoutParams,它的構造函數只有兩個參數,而LinearLayout.LayoutParams有三個參數的構造函數。但是,正如下面已經指出的那樣,這不是你問題的根源。 – skUDA 2012-07-13 20:11:58