无法从我的片段中的自定义对话框中获取字符串值

时间:2016-06-22 13:54:04

标签: java android android-layout android-fragments

我有我的片段,用户现在可以将点发送给另一个用户我需要创建自定义对话框,用户需要重新输入他的图钉。我按照几个教程完成了它,但值总是为空;

    public void onViewCreated(View view, Bundle savedInstanceState) {
    LayoutInflater inflater = LayoutInflater.from(getContext());
    View confirmation=inflater.inflate(R.layout.confirmation,null);
    pin  = (EditText) confirmation.findViewById(R.id.PinChecker);

    }


    SendPointsButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            AlertDialog.Builder builder = new AlertDialog.Builder(getContext());

            builder.setView(R.layout.confirmation);

            builder.setPositiveButton("DA", new    DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    pinCheck= String.valueOf(pin.getText().toString());
                    Log.d("Pin",pinCheck);
} 

我想将pin(EditText)的值分配给名为pinCheck的字符串;

3 个答案:

答案 0 :(得分:2)

我认为你应该将膨胀的布局(确认)传递给builder.setView(),如下所示:

  final View confirmation=inflater.inflate(R.layout.confirmation,null);
  pin  = (EditText) confirmation.findViewById(R.id.PinChecker);

....


SendPointsButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());

        builder.setView(confirmation);

        builder.setPositiveButton("DA", new    DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                pinCheck= String.valueOf(pin.getText().toString());
                Log.d("Pin",pinCheck);
} 

希望这会有所帮助。

答案 1 :(得分:1)

使用这个想法......

 builder.setPositiveButton("DA", new    DialogInterface.OnClickListener() {
....................

        Dialog D = (Dialog) dialog;
                                    //This is the input I can't get text from
                                    EditText inputTemp = (EditText) D.findViewById(R.id.input_text);

    pinCheck= String.valueOf(inputTemp.getText().toString());

........
}

我希望你能得到它..

答案 2 :(得分:0)

尝试使用Dialog元素代替View

访问该元素
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
AlertDialog dialog =builder.create();
dialog.setContentView(confirmation);
..........
dialog.show();

使用

访问您的pin
pin  = (EditText) dialog.findViewById(R.id.PinChecker);