DialogFragment&中的InvocationTargetException NumberPicker

时间:2013-07-12 15:53:41

标签: android android-alertdialog android-dialogfragment android-inflate numberpicker

我正在尝试在对话框中显示一个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>
    
  • DialogFragment定义:

    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();
       }
    }
    
  • 来自主要活动的电话:

    public void openNumberPicker(){
         FragmentManager fm = getSupportFragmentManager();
         NumberPickerCustomDialog npc = new NumberPickerCustomDialog();
         npc.show(fm, "fragment_number_picker");
    }
    

我收到一个InvocationTargetException,但我无法使其正常工作。

有什么想法吗?谢谢!

1 个答案:

答案 0 :(得分:0)

尝试更改您正在使用的上下文:

context = getActivity().getApplicationContext();

相反,您需要活动自己的上下文:

context = getActivity();