有一些问题已经接近这个问题,但它们对我没有太大帮助。所以来了一个新的。
我有一个活动有两个标签。每个选项卡都包含一个ListFragment(确切地说是SherlockListFragment)。一个选项卡显示购物列表对象列表,另一个选项卡显示配方对象列表。现在,我要创建一个对话框片段,用于重命名列表、配方或以后可能添加到应用程序中的任何其他对象。
这里提供的解决方案听起来很有希望,但是因为listframent不能注册来监听来自对话框的点击,所以我应该让我的活动来监听它们,这并不理想,因为这样我的片段就不独立了。
How to get data out of a general-purpose dialog class
理想情况下,我希望我的重命名对话框尽可能独立和可重用。到目前为止,我只发明了一种方法。将对象类名和id发送到对话框,然后使用switch case从数据库中获取正确的对象。这样对话框就可以自己更新对象名(如果对象有rename方法)。但对数据库的重新查询听起来只是转储,因为listFragment已经有了对象。然后对话框需要在开关中为每种新对象添加一个新的大小写。
有什么想法吗?
最佳答案
实际上,我刚刚创建了一个类似于您所要求的对话片段。我是为一个相当大的应用程序,它越来越荒谬的对话侦听器数量我们的主要活动扩展只是为了听一个对话的结果。
为了使一些东西更灵活一些,我转而使用来自谷歌番石榴并发库的listenablefuture。
我创建了以下抽象类以供使用:
public abstract class ListenableDialogFragment<T> extends DialogFragment implements ListenableFuture<T> {
private SettableFuture<T> _settableFuture;
public ListenableDialogFragment() {
_settableFuture = SettableFuture.create();
}
@Override
public void addListener(Runnable runnable, Executor executor) {
_settableFuture.addListener(runnable, executor);
}
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
return _settableFuture.cancel(mayInterruptIfRunning);
}
@Override
public boolean isCancelled() {
return _settableFuture.isCancelled();
}
@Override
public boolean isDone() {
return _settableFuture.isDone();
}
@Override
public T get() throws InterruptedException, ExecutionException {
return _settableFuture.get();
}
@Override
public T get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
return _settableFuture.get(timeout, unit);
}
public void set(T value) {
_settableFuture.set(value);
}
public void setException(Throwable throwable) {
_settableFuture.setException(throwable);
}
// Resets the Future so that it can be provided to another call back
public void reset() {
_settableFuture = SettableFuture.create();
}
@Override
public void onDismiss(DialogInterface dialog) {
// Cancel the future here in case the user cancels our of the dialog
cancel(true);
super.onDismiss(dialog);
}
使用这个类,我可以创建自己的自定义对话框片段,并像这样使用它们:
ListenableDialogFragment<int> dialog = GetIdDialog.newInstance(provider.getIds());
Futures.addCallback(dialog, new FutureCallback<int>() {
@Override
public void onSuccess(int id) {
processId(id);
}
@Override
public void onFailure(Throwable throwable) {
if (throwable instanceof CancellationException) {
// Task was cancelled
}
processException(throwable);
}
});
这里getiddialog是listenabledialogfragment的自定义实例。如果需要,我可以重用同一个对话框实例,方法是在onSuccess和onFailure方法中调用dialog.reset,以确保重新加载内部future以添加回回调。
我希望这能帮到你。
编辑:抱歉,忘记添加了,在您的对话框中,您可以实现一个点击式监听器,该监听器执行类似的操作来触发未来:
private class SingleChoiceListener implements DialogInterface.OnClickListener {
@Override
public void onClick(DialogInterface dialog, int item) {
int id = _ids[item];
// This call will trigger the future to fire
set(id);
dismiss();
}
}
关于android - 如何设计可重用的DialogFragment,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17318237/