【问题标题】:prevent data being loaded everytime in DialogFragment防止每次在 DialogFragment 中加载数据
【发布时间】:2012-03-22 10:23:34
【问题描述】:

我在Android Compatibility Support Package 的帮助下使用 DialogFragment 创建了一个自定义 AlergDialog

在我的自定义对话框中,我在对话框中有一个列表视图,并且列表视图的内容是从 Android 中的 Sqlite 数据库加载的。此对话框仅从片段内的列表视图中弹出。

现在,每当我单击 listview(位于片段内)时,都会出现一个对话框,其中数据成功进入 listview,但每次我每次按下 listitem(位于片段内)时,数据都会从对话框列表视图中的数据库 bcoz onCreate is being called every time 所以我想要的是 data should be loaded at once for all listitem of listview which is inside of fragment.

代码

每当点击片段中的列表项时,我都会调用自定义 DialogFragment

DalogFragment newFragment = TemplateToContact.newInstance("hi");
newFragment.show(getFragmentManager(), "dialog");

DialogFragment 的 OnCreate

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        contactDB = new ContactDB(getActivity().getApplicationContext());
    contactDataList = contactDB.getAllContacts();
        templateContactAdapter = new TemplateContactAdapter();

    }

在 OnCreateDialog 中我创建了一个自定义警报对话框,设置适配器并返回它

@Override
 public Dialog onCreateDialog(Bundle savedInstanceState) {

   LayoutInflater factory = LayoutInflater.from(getActivity());         
   View v = factory.inflate(R.layout.cdialog, null);
   builder = new AlertDialog.Builder(getActivity());

   builder.setView(v);

   templateContactDlg = builder.create();                

   templateContactList = (ListView)v.findViewById(R.id.contactDlgList);            

   templateContactList.setAdapter(templateContactAdapter);

   return templateContactDlg;

  }

【问题讨论】:

    标签: android android-fragments android-dialog android-dialogfragment


    【解决方案1】:

    您说您使用 DialogFragment,但您的代码显示 AlertDialog。 Here 是一个如何使用 DialogFragment 的示例。 Google Android 团队建议您使用 DialogFragment,而不是 AlertDialog。

    添加:

    @覆盖 public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); if (savedInstanceState != null) { aboutFile = savedInstanceState.getString(FILE_NAME); } } @覆盖 公共无效 onSaveInstanceState(捆绑 outState){ outState.putString(FILE_NAME, aboutFile); }

    如需注入帮助类,请阅读 this,例如。

    【讨论】:

    • 我已经扩展了 DialogFragment 类,并且在该类中我已经覆盖了 onCreateDialog 方法,并且我正在屏蔽 AlertDialog 框并返回它,你可以在你给我的链接中看到相同的内容,遍历到 AlertDialog 部分
    • onStop 和 onCreate 之间的数据是否使用 savedInstanceState 进行保存?我通常在我的片段和 dao 之间有一个数据管理器类。管理器类是@Injected,它缓存数据。
    • 我不知道怎么用,请问有sn-p示例代码吗
    • 在我的原始答案中添加了它,因为我无法在评论中格式化或使用 @。
    猜你喜欢
    • 1970-01-01
    • 2018-07-21
    • 2021-05-19
    • 2020-02-13
    • 2014-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多