gpt4 book ai didi

java - 在 Activity 中为 DialogFragment 设置监听器

转载 作者:行者123 更新时间:2023-12-02 03:43:50 24 4
gpt4 key购买 nike

我正在尝试在我的 DialogFragment 上的 Activity 中实现一个监听器(它有 3 个 numberPicker 小部件元素),该监听器将用于在 Activity 的 textView 中设置值,并且我不想将此 Fragment 类设置为内部类Activity 并在“确定”按钮的 OnClickListener 中设置 TextView ,因为在这种情况下我必须使 View 静态,这是不可取的。我知道 NumberPicker 类有一个 onValueChange 监听器,但是如何设置一个从 3 个选择器元素获取值的监听器。任何在 Activity 中实现此类监听器的帮助将不胜感激。

 public class PickerDialog extends DialogFragment {
NumberPicker numberPicker;
NumberPicker numberPicker2;
NumberPicker numberPicker3;
public static PickerDialog newInstance() {
PickerDialog frag = new PickerDialog ();
return frag;
}


@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
View child = getActivity().getLayoutInflater().inflate(R.layout.dialog, null);
numberPicker = child.findViewById(R.id.numberPicker1);
numberPicker2 = child.findViewById(R.id.numberPicker2);
numberPicker3 = child.findViewById(R.id.numberPicker3);

numberPicker.setMinValue(0);
numberPicker.setMaxValue(59);
numberPicker3.setMinValue(0);
numberPicker3.setMaxValue(59);

numberPicker2.setMinValue(0);
numberPicker2.setMaxValue(59);

AlertDialog.Builder builder;
builder = new AlertDialog.Builder(getActivity(), R.style.Theme_Material_Dialog_Alert);


builder.setTitle("Choose Value");


builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {

dismiss();
}
});

builder.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dismiss();

}
});

builder.setView(child);
return builder.create();
}




}

最佳答案

您可以创建一个 Listener 接口(interface),该接口(interface)在您的 Activity 中实现,并通过对 Activity 的引用在 DialogFragment 中使用。像这样的东西:

public class MyActivity extends Activity implements NumberPickerListener {
...
@Override
public void onValuesPicked(int first, int second, int third) {
//Do work here.
}
...
}

界面:

interface NumberPickerLisener {
void onValuesPicked(int first, int second, int third);
}

在您的 fragment 中:

public class PickerDialog extends DialogFragment {

NumberPickerListener listener;

...

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
View child = getActivity().getLayoutInflater().inflate(R.layout.dialog, null);
listener = (MyActivity)getActivity();

...

builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
listener.onValuesPicked(numberPicker.getValue(), numberPicker2.getValue(), numberPicker3.getValue());
dismiss();
}
});

...
}




}

关于java - 在 Activity 中为 DialogFragment 设置监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56821013/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com