我在片段中有一个按钮,当我点击我需要打开一个对话框,其中填充了listview项目,但是我无法打开带有列表项的对话框
final ListView lv = (ListView) view.findViewById(R.id.mylist);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Dialog dialog = new Dialog(getActivity());
dialog.setContentView(R.layout.list_view);
dialog.setTitle("Custom Dialog");
ArrayAdapter<String> selectedAdapter = new ArrayAdapter<String>(getActivity(), R.layout.list_view,R.id.text, event);
selectedAdapter.setNotifyOnChange(true);
lv.setAdapter(selectedAdapter);
dialog.show();
}
});
我的列表视图
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical|center_horizontal"
android:text=""
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#FFFFFF" />
<ListView
android:id="@+id/mylist"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:divider="#b5b5b5"
android:dividerHeight="5dp" />
</LinearLayout>
感谢任何帮助。
答案 0 :(得分:4)
添加dialog.show()
以使其显示在屏幕上!
修改强>
好的,问题是你在创建对话框之前找到了listview 。因此,lv
不是对任何对象的有效引用。
在设置内容视图之前移动findViewById
:
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Dialog dialog = new Dialog(getActivity());
dialog.setContentView(R.layout.list_view);
ListView lv = (ListView) dialog.findViewById(R.id.mylist);
dialog.setTitle("Custom Dialog");
ArrayAdapter<String> selectedAdapter = new ArrayAdapter<String>(getActivity(), R.layout.list_view,R.id.text, event);
selectedAdapter.setNotifyOnChange(true);
lv.setAdapter(selectedAdapter);
dialog.show();
}
});
答案 1 :(得分:2)
像这样初始化ListView。
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Dialog dialog = new Dialog(getActivity());
dialog.setContentView(R.layout.list_view);
dialog.setTitle("Custom Dialog");
ListView lv = (ListView) dialog.findViewById(R.id.mylist);
ArrayAdapter<String> selectedAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, event);
selectedAdapter.setNotifyOnChange(true);
lv.setAdapter(selectedAdapter);
dialog.show();
}
});
编辑:您有一个自定义对话框。您有一个带有textview和listview的布局list_view
。因此,要初始化listview,您应该使用对话框对象来初始化listview
与初始化textview相似
TextView tv = (TextView)dialog.findViewById(R.id.text);