我试图在对话框中显示一个 NumberPicker,以便让用户选择一个介于 0 和 10 之间的值。这是我试图让它工作的第二天。
这就是我所拥有的:
fragment_number_picker(布局):
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/numberPickerFragmentLinearLayout" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center" android:orientation="horizontal" > <NumberPicker android:id="@+id/numberPickerInFragment" android:layout_width="wrap_content" android:layout_height="48dp" android:orientation="horizontal" /> </LinearLayout>
对话框片段定义:
public class NumberPickerCustomDialog extends DialogFragment { Context context; public NumberPickerCustomDialog() {} @Override public Dialog onCreateDialog(Bundle savedInstanceState) { context = getActivity().getApplicationContext(); AlertDialog.Builder builder = new AlertDialog.Builder(context); LayoutInflater li = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); // Inflate and set the layout for the dialog View view = li.inflate(R.layout.fragment_number_picker, null); builder // Set view: .setView(view) // Add action buttons .setPositiveButton(R.string.accept, new DialogInterface.OnClickListener(){ @Override public void onClick(DialogInterface dialog, int id) { // Accept number } }) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener(){ public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); } }); NumberPicker np = (NumberPicker) view.findViewById(R.id.numberPickerInFragment); np.setMaxValue(200); np.setMinValue(0); np.setFocusable(true); np.setFocusableInTouchMode(true); return builder.create(); } }
从主 Activity 调用:
public void openNumberPicker(){ FragmentManager fm = getSupportFragmentManager(); NumberPickerCustomDialog npc = new NumberPickerCustomDialog(); npc.show(fm, "fragment_number_picker"); }
我得到一个 InvocationTargetException 并且我无法让它工作。
有任何想法吗?谢谢!