任何人都可以帮助我,如何在对话框中添加ListView。我正在尝试在customDialog中添加ListView但是收到错误.. ListView没有出现。
答案 0 :(得分:4)
您可以使用DialogFragment向对话框添加自定义布局。
你的Fragment需要扩展DialogFragment(app.v4 one)类:
<强> BlankFragment.java 强>
public class BlankFragment extends DialogFragment {
private ListView listView;
public BlankFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_blank, container, false);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
listView = view.findViewById(R.id.f_blank_list);
List<String> strings = Arrays.asList("Hello", "World", "Bye");
ArrayAdapter<String> arrayAdapter
= new ArrayAdapter<>(getContext(), android.R.layout.simple_list_item_1, strings);
listView.setAdapter(arrayAdapter);
}
}
然后,您可以在对话框中放置任何内容,将其设置为布局:
<强> fragment_blank.xml 强>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="10dp"
tools:context="com.example.myapplication.BlankFragment">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/hello_blank_fragment" />
<ListView
android:id="@+id/f_blank_list"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</ListView>
</LinearLayout>
最后,您需要在MainActivity的交易中显示它:
<强> MainActivity.java 强>
public class MainActivity extends AppCompatActivity {
private static final String BLANK_FRAGMENT_TAG = "FRAGMENT_TAG";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void loadFragment(View view) {
BlankFragment blankFragment = new BlankFragment();
blankFragment.show(getSupportFragmentManager(), BLANK_FRAGMENT_TAG);
}
}
结果如下:
答案 1 :(得分:1)
您可以在此处找到对话框的文档:
https://developer.android.com/guide/topics/ui/dialogs.html
对于您可以使用的对话框中的列表:
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.pick_color)
.setItems(R.array.colors_array, new
DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// The 'which' argument contains the index position
// of the selected item
}
});
return builder.create();
}