实现OnClickListener DialogFragment接口接口、OnClickListener、DialogFragment

2023-09-03 22:02:29 作者:洋气的抖音英文名 抖音最火英文

我需要建立一个DialogFragment返回用户输入的对话框的活动。 对话需要调用在被调用时,在一个列表视图的元素被点击了OnClickListener。 所述DialogFragment(用户的输入)的返回值应该是直接可用在OnClickListener在活动

我试图坚持官方文档来实现这一点: HTTP: //developer.android.com/guide/topics/ui/dialogs.html#PassingEvents

我需要像下面这样,因为我不工作,不知道如何使匿名OnClickListener实现CustomNumberPicker类的接口。 据我所知实现该接口是必要的,以便从DialogFragment找回数据的活动。

主要活动:

 公共类MainAcitivity扩展ActionBarActivity {
    [...]

    //列表视图的ArrayAdapter
    私有类ListViewArrayAdapter扩展ArrayAdapter<运动> {
        公共ListViewArrayAdapter(上下文的背景下,ArrayList的<运动>习题){
            超(背景下,0,行使);
        }

        @覆盖
        公共查看getView(INT位置,查看convertView,ViewGroup中父){
            [...]

            如果(convertView == NULL){
                convertView = LayoutInflater.from(的getContext())膨胀(R.layout.item_workoutdetail,父母,假)。
            }

            TextView的tvSets =(TextView中)convertView.findViewById(R.id.tvWorkoutExerciseSets);
            tvSets.setText(sets.toString());

            // OnClickListener在ListView中的每一个元素
            tvSets.setOnClickListener(新View.OnClickListener(){
                @覆盖
                公共无效的onClick(视图v){
                    //这就是对话应该叫和
                    //从对话框中用户输入应返还
                    DialogFragment numberpicker =新CustomNumberPicker();
                    numberpicker.show(MainActivity.this.getSupportFragmentManager(),NoticeDialogFragment);
                }

                //这里我想实现CustomNumberPicker接口
                //为了得到在对话框中输入的用户输入
            });

            返回convertView;
        }
    }
}
 

CustomNumberPicker(基本上是相同的文档):

 公共类CustomNumberPicker扩展DialogFragment {

    公共接口NoticeDialogListener {
        公共无效onDialogPositiveClick(DialogFragment对话);
        公共无效onDialogNegativeClick(DialogFragment对话);
    }

    //使用该接口的这个实例提供操作事件
    NoticeDialogListener mListener;

    //覆盖的Fragment.onAttach()方法来实例化NoticeDialogListener
    @覆盖
    公共无效onAttach(活动活动){
        super.onAttach(活动);
        //验证主机活动实现的回调接口
        尝试 {
            //实例化NoticeDialogListener,所以我们可以将事件发送到主机
            mListener =(NoticeDialogListener)的活动;
        }赶上(ClassCastException异常E){
            //活动不实现接口,抛出异常
            抛出新ClassCastException异常(activity.toString()
                +必须实现NoticeDialogListener);
        }
    }

    @覆盖
    公共对话onCreateDialog(包savedInstanceState){
        //使用生成器类简单的对话框建设
        AlertDialog.Builder建设者=新AlertDialog.Builder(getActivity());
        builder.setMessage(集)
            .setPositiveButton(设置,新DialogInterface.OnClickListener(){
                    公共无效的onClick(DialogInterface对话框,INT ID){
                        //这里返回的东西的活动?
                    }
                })
                .setNegativeButton(CANCLE,新DialogInterface.OnClickListener(){
                    公共无效的onClick(DialogInterface对话框,INT ID){
                        //用户取消了对话框
                    }
                });
        //创建AlertDialog对象,并返回其
        返回builder.create();
    }
}
 

解决方案

这样的事情?

 公共类CustomNumberPicker扩展DialogFragment {
    私人NoticeDialogListener NDL;

    公共接口NoticeDialogListener {
        公共无效onDialogPositiveClick(DialogFragment对话);
        公共无效onDialogNegativeClick(DialogFragment对话);
    }

    //添加自定义的构造函数,以便你有一个初始化NoticeDialogListener
    公共CustomNumberPicker(NoticeDialogListener NDL){
        超();
            this.ndl = NDL;
    }

    //一定要保持一个空的构造
    公共CustomNumberPicker(){
        超();
    }

    //使用该接口的这个实例提供操作事件
    NoticeDialogListener mListener;

    //覆盖的Fragment.onAttach()方法来实例化NoticeDialogListener
    @覆盖
    公共无效onAttach(活动活动){
        super.onAttach(活动);
        //删除verfis如果你的活动有附加的,因为你想将其附加到你的列表视图的onClick的DialogListener检查()
    }

    @覆盖
    公共对话onCreateDialog(包savedInstanceState){
        //使用生成器类简单的对话框建设
        AlertDialog.Builder建设者=新AlertDialog.Builder(getActivity());
        builder.setMessage(集)
            .setPositiveButton(设置,新DialogInterface.OnClickListener(){
                    公共无效的onClick(DialogInterface对话框,INT ID){
                        ndl.onDialogPositiveClick(对话);
                    }
                })
                .setNegativeButton(CANCLE,新DialogInterface.OnClickListener(){
                    公共无效的onClick(DialogInterface对话框,INT ID){
                       ndl.onDialogNegativeClick(对话);
                    }
                });
        //创建AlertDialog对象,并返回其
        返回builder.create();
    }
}
 
Android的四种点击事件之Activity实现OnClickListener接口

,然后你的ListView的onClick变为:

  tvSets.setOnClickListener(新View.OnClickListener(){
                @覆盖
                公共无效的onClick(视图v){
                    //这就是对话应该叫和
                    //从对话框中用户输入应返还
                    //
                    //


                    DialogFragment numberpicker =新CustomNumberPicker(新NoticeDialogListener(){

            @覆盖
            公共无效onDialogPositiveClick(DialogFragment对话){
                //你想要做柜面积极的点击什么

            }

            @覆盖
            公共无效onDialogNegativeClick(DialogFragment对话){
               //你想要做柜面负点击什么

            }
        });
                    numberpicker.show(MainActivity.this.getSupportFragmentManager(),NoticeDialogFragment);
                }

                //这里我想实现CustomNumberPicker接口
                //为了得到在对话框中输入的用户输入
            });
 

请阅读我有意见added.And它甚至可以进一步优化,因为你真的不需要一个完整的对话实例来获得你所需要的值。

修改一个可能的优化可能是:

更改监听器接口:

 公共接口NoticeDialogListener {
        公共无效onDialogPositiveClick(字符串输出);
        公共无效onDialogNegativeClick(字符串输出);
       //或任何你想要的输出形式
    }
 

然后相应地修改实现的方法。

I need to build a DialogFragment which returns user input from the dialog to an activity. The dialog needs to be called in an OnClickListener which gets called when an element in a listview gets clicked. The return value of the DialogFragment (the input of the user) should be directly available in the OnClickListener in the activity.

I tried to implement this by sticking to the official docs: http://developer.android.com/guide/topics/ui/dialogs.html#PassingEvents

I need something like the following which doesn't work since I don't know how to make the anonymous OnClickListener implement the interface of the CustomNumberPicker class. As far as I know implementing the interface is necessary in order to get data from the DialogFragment back to the Activity.

Main Activity:

public class MainAcitivity extends ActionBarActivity {
    [...]

    // ArrayAdapter of the Listview
    private class ListViewArrayAdapter extends ArrayAdapter<Exercise> {
        public ListViewArrayAdapter(Context context, ArrayList<Exercise> exercises) {
            super(context, 0, exercises);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            [...]

            if (convertView == null) {
                convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_workoutdetail, parent, false);
            }

            TextView tvSets = (TextView) convertView.findViewById(R.id.tvWorkoutExerciseSets);
            tvSets.setText(sets.toString());

            // OnClickListener for every element in the ListView
            tvSets.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // This is where the Dialog should be called and
                    // the user input from the Dialog should be returned
                    DialogFragment numberpicker = new CustomNumberPicker();
                    numberpicker.show(MainActivity.this.getSupportFragmentManager(), "NoticeDialogFragment");
                }

                // Here I would like to implement the interface of CustomNumberPicker
                // in order to get the user input entered in the Dialog
            });

            return convertView;
        }
    }
}

CustomNumberPicker (basically the same as in the docs):

public class CustomNumberPicker extends DialogFragment {

    public interface NoticeDialogListener {
        public void onDialogPositiveClick(DialogFragment dialog);
        public void onDialogNegativeClick(DialogFragment dialog);
    }

    // Use this instance of the interface to deliver action events
    NoticeDialogListener mListener;

    // Override the Fragment.onAttach() method to instantiate the NoticeDialogListener
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        // Verify that the host activity implements the callback interface
        try {
            // Instantiate the NoticeDialogListener so we can send events to the host
            mListener = (NoticeDialogListener) activity;
        } catch (ClassCastException e) {
            // The activity doesn't implement the interface, throw exception
            throw new ClassCastException(activity.toString()
                + " must implement NoticeDialogListener");
        }
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Use the Builder class for convenient dialog construction
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setMessage("Sets")
            .setPositiveButton("set", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        // Return stuff here to the activity?
                    }
                })
                .setNegativeButton("cancle", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        // User cancelled the dialog
                    }
                });
        // Create the AlertDialog object and return it
        return builder.create();
    }
}

解决方案

Something like this?

public class CustomNumberPicker extends DialogFragment {
    private NoticeDialogListener ndl;

    public interface NoticeDialogListener {
        public void onDialogPositiveClick(DialogFragment dialog);
        public void onDialogNegativeClick(DialogFragment dialog);
    }

    //add a custom constructor so that you have an initialised NoticeDialogListener
    public CustomNumberPicker(NoticeDialogListener ndl){
        super();
            this.ndl=ndl;
    }

    //make sure you maintain an empty constructor
    public CustomNumberPicker( ){
        super();
    }

    // Use this instance of the interface to deliver action events
    NoticeDialogListener mListener;

    // Override the Fragment.onAttach() method to instantiate the NoticeDialogListener
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        //remove the check that verfis if your activity has the DialogListener Attached because you want to attach it into your list view onClick()
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Use the Builder class for convenient dialog construction
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setMessage("Sets")
            .setPositiveButton("set", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        ndl.onDialogPositiveClick(dialog);
                    }
                })
                .setNegativeButton("cancle", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                       ndl.onDialogNegativeClick(dialog);
                    }
                });
        // Create the AlertDialog object and return it
        return builder.create();
    }
}

and then your listView onClick becomes:

tvSets.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // This is where the Dialog should be called and
                    // the user input from the Dialog should be returned
                    // 
                    // 


                    DialogFragment numberpicker = new CustomNumberPicker(new NoticeDialogListener() {

            @Override
            public void onDialogPositiveClick(DialogFragment dialog) {
                //What you want to do incase of positive click

            }

            @Override
            public void onDialogNegativeClick(DialogFragment dialog) {
               //What you want to do incase of negative click

            }
        };);
                    numberpicker.show(MainActivity.this.getSupportFragmentManager(), "NoticeDialogFragment");
                }

                // Here I would like to implement the interface of CustomNumberPicker
                // in order to get the user input entered in the Dialog
            });

Do read the comments I have added.And it can even be further optimized because you really dont need an entire dialog instance to get the values you need.

EDIT a possible optimization could be:

Changing the Listener interface to :

public interface NoticeDialogListener {
        public void onDialogPositiveClick(String output);
        public void onDialogNegativeClick(String output);
       //or whatever form of output that you want
    }

Then modify the implemented methods accordingly.