对话框片段:输入值时的响应

时间:2015-03-10 12:08:31

标签: java android android-activity android-fragments android-studio

我需要帮助知道如何在输入值然后按下okay按钮或取消按钮时进行dialogfragment动作。

以下是课程ActivityA.javaBasicDialogFragment.javafragment_basic_dialog.xmlactivity_a.xml

这个问题所需的所有代码。提前谢谢。

ActivityA

    package internal.android.com.helloworld;

    import android.content.Intent;
    import android.support.v7.app.ActionBarActivity;
    import android.os.Bundle;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.TextView;
    import android.widget.Toast;


    public class ActivityA extends ActionBarActivity implements BasicDialogFragment.OnNameEnteredListener {

        private Button dialogKnapp = null;
        private TextView textA = null;
        private TextView textA2 = null;
        private EditText editA2 = null;
        private Button buttonAB = null;
        private Button buttonAC = null;
        private Button buttonAD = null;
        private Button buttonCancel = null;
        private Button buttonOK = null;
        private EditText dialog_fornavn = null;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_a);
            dialogKnapp = (Button) findViewById(R.id.dialog_knapp);
            buttonCancel = (Button) findViewById(R.id.buttonCancel);
            buttonOK = (Button) findViewById(R.id.buttonOK);
            dialog_fornavn = (EditText) findViewById(R.id.dialog_fornavn);
            textA = (TextView) findViewById(R.id.textA);
            textA2 = (TextView) findViewById(R.id.textA2);
            editA2 = (EditText) findViewById(R.id.editA2);
            buttonAB = (Button) findViewById(R.id.buttonAB);
            buttonAC = (Button) findViewById(R.id.buttonAC);
            buttonAD = (Button) findViewById(R.id.buttonAD);


            Intent intent = getIntent();
            String navn = intent.getStringExtra("navnet");
            textA2.setText(navn);

            buttonAB.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startAB();
                }
            });

            buttonAC.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startAC();
                }
            });

            buttonAD.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startAD();
                }
            });

            dialogKnapp.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startDialog();
                }
            });

        }

        private void startAB() {
            String navn = editA2.getText().toString().toUpperCase();
            Intent intent = new Intent(ActivityA.this, ActivityB.class);
            intent.putExtra("navnet", navn);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        }

        private void startAC() {
            String navn = editA2.getText().toString().toUpperCase();
            Intent intent = new Intent(ActivityA.this, ActivityC.class);
            intent.putExtra("navnet", navn);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        }

        private void startAD() {
            String navn = editA2.getText().toString().toUpperCase();
            Intent intent = new Intent(ActivityA.this, ActivityD.class);
            intent.putExtra("navnet", navn);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        }

        private void startDialog() {
            BasicDialogFragment bdf = new BasicDialogFragment();
            bdf.show(getFragmentManager(), "basic");
        }

        public void OnFragmentInteractionListener(String nameEntered){
            visTekst();
        }

        private void visTekst() {
            if(buttonOK.isPressed()){
                textA2.setText(dialog_fornavn.getText());
                Toast melding = Toast.makeText(getApplicationContext(),
                        dialog_fornavn.getText(), Toast.LENGTH_SHORT);
                melding.show();
            } else if(buttonCancel.isPressed()){
                startAB();
            }
        }

        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.menu_main, menu);
            return true;
        }

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            // Handle action bar item clicks here. The action bar will
            // automatically handle clicks on the Home/Up button, so long
            // as you specify a parent activity in AndroidManifest.xml.
            Toast toast = Toast.makeText(getApplicationContext(), "Activity A",
                    Toast.LENGTH_SHORT);
            switch (item.getItemId()) {
                case R.id.menu_item_1:
                    toast.setText("Activity A");
                    toast.show();
                    return true;
                case R.id.menu_item_2:
                    toast.setText("Activity B");
                    toast.show();
                    startAB();
                    return true;
                case R.id.menu_item_3:
                    toast.setText("Activity C");
                    toast.show();
                    startAC();
                    return true;
                case R.id.menu_item_4:
                    toast.setText("Activity D");
                    toast.show();
                    startAD();
                    return true;
                case R.id.action_settings:
                    toast.setText("Settings");
                    toast.show();
                    return true;
                default:
                    return super.onOptionsItemSelected(item);
            }

        }

    }

BasicDialogFragment.java

import android.app.Activity;
import android.app.DialogFragment;
import android.net.Uri;
import android.os.Bundle;
import android.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;


/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link BasicDialogFragment.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link BasicDialogFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class BasicDialogFragment extends DialogFragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p/>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */

    public interface OnNameEnteredListener {
        public void OnFragmentInteractionListener(String nameEntered);
    }

    private OnNameEnteredListener mListener;

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment BasicDialogFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static BasicDialogFragment newInstance(String param1, String param2) {
        BasicDialogFragment fragment = new BasicDialogFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    public BasicDialogFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v = inflater.inflate(R.layout.fragment_basic_dialog, container, false);
        this.getDialog().setTitle("First Name");
        return v;
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.OnFragmentInteractionListener("uri");
        }
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (OnNameEnteredListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }


}

fragment_basic_dialog.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" tools:context="no.hit.kvisli.heiverden.BasicDialogFragment"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:padding="10dp" android:orientation="vertical" >
    <EditText
        android:id="@+id/dialog_fornavn"
        android:layout_width="match_parent" android:layout_height="wrap_content"
        android:textSize="24dp" android:textColor="@android:color/holo_red_dark"
        android:hint="Skriv fornavn her" android:inputType="textPersonName" />
    <LinearLayout
        android:layout_width="match_parent" android:layout_height="wrap_content"
        android:padding="10dp" android:orientation="horizontal" >
        <Button
            android:id="@+id/buttonCancel" android:text="Cancel"
            android:layout_width="wrap_content" android:layout_height="wrap_content" />
        <Button
            android:id="@+id/buttonOK" android:text="OK"
            android:layout_width="wrap_content" android:layout_height="wrap_content" />
    </LinearLayout>
</LinearLayout>

activity_a.xml

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:fillViewport="true">
<LinearLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="@color/farge_A"
    tools:context=".ActivityA">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Activity A"
        android:id="@+id/textA"
        style="@style/Overskrift"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/textA2"
        style="@style/Overskrift"/>

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/editA2"
        style="@style/EditTekst"
        android:hint="Skriv noe her"
        android:layout_marginLeft="120dp"
        android:layout_marginTop="50dp"/>

    <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="horizontal"
        android:layout_marginTop="150dp"
        android:layout_marginLeft="50dp"
        tools:context=".ActivityA">

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Dialog"
            android:id="@+id/dialog_knapp"
            android:background="@color/dialog_knapp"
            android:layout_alignParentBottom="true"
            android:layout_centerHorizontal="true"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Go to B"
        android:id="@+id/buttonAB"
        android:background="@color/farge_B"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Go to C"
        android:id="@+id/buttonAC"
        android:background="@color/farge_C"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"/>

        <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Go to D"
        android:id="@+id/buttonAD"
        android:background="@color/farge_D"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"/>

    </LinearLayout>
</LinearLayout>
</ScrollView>

3 个答案:

答案 0 :(得分:0)

如果我正确阅读,您的BasicDialogFragment代码就像this

然后您需要做的就是添加

public void OnNameEntered(String nameEntered){
            //Do Something Here
}

ActivityA.java

修改

修改以下功能如下:

private void visTekst(String nameEntered) {
            if(buttonOK.isPressed()){
                textA2.setText(nameEntered);
                Toast melding = Toast.makeText(getApplicationContext(),
                        dialog_fornavn.getText(), Toast.LENGTH_SHORT);
                melding.show();
            } else if(buttonCancel.isPressed()){
                startAB();
            }
        }

并将其命名为

 public void OnFragmentInteractionListener(String nameEntered){
            visTekst(nameEntered);
        }

您需要按照使用过的代码中提到的设置侦听器

BasicDialogFragment

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v = inflater.inflate(R.layout.fragment_basic_dialog, container, false);
        this.getDialog().setTitle("First Name");


    buttonCancel = (Button) findViewById(R.id.buttonCancel);
    buttonOK = (Button) findViewById(R.id.buttonOK);
buttonCancel.setOnClickListner(new View.OnClickListener(View v){
      onButtonPressed(/*Your custom URI*/Uri uri);
});
buttonOK .setOnClickListner(new View.OnClickListener(View v){
      onButtonPressed(/*Your custom URI*/Uri uri);
});
   return v;
    }

答案 1 :(得分:0)

对于此问题,有两种方法,一种是直接cast托管Activity以获取活动实例。另一个是使用DialogFragment中定义但由托管Activity实现的一个界面。

有关详情,请关注我之前的帖子Call activity from DialogFragment

答案 2 :(得分:0)

//Here is the answer. Took a while but got it to the end, thanks for your help.

    //ActivityA
    import android.app.FragmentManager;
    import android.content.Intent;
    import android.support.v7.app.ActionBarActivity;
    import android.os.Bundle;
    import android.text.Editable;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.TextView;
    import android.widget.Toast;


    public class ActivityA extends ActionBarActivity implements BasicDialogFragment.Communicator {

        private Button dialogKnapp = null;
        private TextView textA = null;
        private TextView textA2 = null;
        private EditText editA2 = null;
        private Button buttonAB = null;
        private Button buttonAC = null;
        private Button buttonAD = null;
        private EditText dialog_fornavn = null;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_a);
            dialogKnapp = (Button) findViewById(R.id.dialog_knapp);
            dialog_fornavn = (EditText) findViewById(R.id.dialog_fornavn);
            textA = (TextView) findViewById(R.id.textA);
            textA2 = (TextView) findViewById(R.id.textA2);
            editA2 = (EditText) findViewById(R.id.editA2);
            buttonAB = (Button) findViewById(R.id.buttonAB);
            buttonAC = (Button) findViewById(R.id.buttonAC);
            buttonAD = (Button) findViewById(R.id.buttonAD);


            Intent intent = getIntent();
            String navn = intent.getStringExtra("navnet");
            textA2.setText(navn);

            buttonAB.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startAB();
                }
            });

            buttonAC.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startAC();
                }
            });

            buttonAD.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startAD();
                }
            });

            dialogKnapp.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startDialog();
                }
            });
        }

        private void startAB() {
            String navn = editA2.getText().toString().toUpperCase();
            Intent intent = new Intent(ActivityA.this, ActivityB.class);
            intent.putExtra("navnet", navn);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        }

        private void startAC() {
            String navn = editA2.getText().toString().toUpperCase();
            Intent intent = new Intent(ActivityA.this, ActivityC.class);
            intent.putExtra("navnet", navn);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        }

        private void startAD() {
            String navn = editA2.getText().toString().toUpperCase();
            Intent intent = new Intent(ActivityA.this, ActivityD.class);
            intent.putExtra("navnet", navn);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        }

        public void startDialog(){
            FragmentManager manager = getFragmentManager();
            BasicDialogFragment basicDialogFragment = new BasicDialogFragment();
            basicDialogFragment.show(manager,"BasicDialogFragment");
        }

        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.menu_main, menu);
            return true;
        }

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            // Handle action bar item clicks here. The action bar will
            // automatically handle clicks on the Home/Up button, so long
            // as you specify a parent activity in AndroidManifest.xml.
            Toast toast = Toast.makeText(getApplicationContext(), "Activity A",
                    Toast.LENGTH_SHORT);
            switch (item.getItemId()) {
                case R.id.menu_item_1:
                    toast.setText("Activity A");
                    toast.show();
                    return true;
                case R.id.menu_item_2:
                    toast.setText("Activity B");
                    toast.show();
                    startAB();
                    return true;
                case R.id.menu_item_3:
                    toast.setText("Activity C");
                    toast.show();
                    startAC();
                    return true;
                case R.id.menu_item_4:
                    toast.setText("Activity D");
                    toast.show();
                    startAD();
                    return true;
                case R.id.action_settings:
                    toast.setText("Settings");
                    toast.show();
                    return true;
                default:
                    return super.onOptionsItemSelected(item);
            }

        }

        @Override
        public void onDialogMessage(Editable message) {
            textA2.setText(message);
        }
    }

//BasicDialogFragment
`import android.app.Activity;
import android.app.DialogFragment;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class BasicDialogFragment extends DialogFragment implements View.OnClickListener{

    private Button buttonCancel = null;
    private Button buttonOK = null;
    private EditText dialog_fornavn = null;
    Communicator communicator;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        communicator= (Communicator) activity;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_basic_dialog, null);
        buttonCancel = (Button) v.findViewById(R.id.buttonCancel);
        buttonOK = (Button) v.findViewById(R.id.buttonOK);
        dialog_fornavn = (EditText) v.findViewById(R.id.dialog_fornavn);
        buttonCancel.setOnClickListener(this);
        buttonOK.setOnClickListener(this);
        setCancelable(true);
        return v;
    }

    @Override
    public void onClick(View v) {
        if(v.getId()==R.id.buttonOK){
            communicator.onDialogMessage(dialog_fornavn.getText());
            dismiss();
        }
        else{
            dismiss();
        }
    }

    interface Communicator{
        public void onDialogMessage(Editable message);
    }

}`
//Thats it, nothing chaged in xml files. Not sure if its good coding but worked for me.