gpt4 book ai didi

Android "Best Practice"从对话框返回值

转载 作者:IT王子 更新时间:2023-10-28 23:40:37 27 4
gpt4 key购买 nike

从复杂的自定义对话框中将值返回给调用 Activity 的“正确”方法是什么 - 例如,文本字段、日期或时间选择器、一堆单选按钮等,以及“保存”和“取消” "按钮?

我在网上看到的一些技术包括:

  • 可以被Activity读取的Dialog派生类中的公共(public)数据成员

  • 公共(public)“获取”访问器。 . . “……” . "

  • 使用 Intent(与 show() 相对)以及 Dialog 类中的处理程序启动对话框,该处理程序从各种控件获取输入并将它们 bundle 起来传递回 Activity ,因此当监听器点击“保存”时,使用 ReturnIntent()

  • 将包传回
  • Activity 中的监听器处理来自对话框中控件的输入,例如,TimePicker 或 DatePicker 的监听器实际上在 Activity 中。在这个方案中,几乎所有的工作都在 Activity 中完成

  • Activity 中的一个 Listener 用于“保存”按钮,然后 Activity 直接询问对话框中的控件; Activity 关闭对话框。

...加上我已经忘记的更多内容。

是否存在被认为是规范正确或“最佳实践”方法的特定技术?

最佳答案

也许我误解了你的问题,但为什么不直接使用内置的监听系统:

builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// run whatever code you want to run here
// if you need to pass data back, just call a function in your
// activity and pass it some parameters
}
})

这就是我一直以来处理对话框数据的方式。

编辑:让我给你一个更具体的例子,它会更好地回答你的问题。我将从这个页面窃取一些示例代码,你应该阅读:

http://developer.android.com/guide/topics/ui/dialogs.html

// Alert Dialog code (mostly copied from the Android docs
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Pick a color");
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
myFunction(item);
}
});
AlertDialog alert = builder.create();

...

// Now elsewhere in your Activity class, you would have this function
private void myFunction(int result){
// Now the data has been "returned" (as pointed out, that's not
// the right terminology)
}

关于Android "Best Practice"从对话框返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4473940/

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