簡體   English   中英

在我的活動(SQLite)中修改數據后如何更新我的片段?

[英]How do I update my Fragment after data modification in my activity (SQLite)?

我在應用程序啟動時填充的 Fragment 中有一個 ListView。 我在我的 newInstance 方法中將 ParcelableArrayList 放在一個 Bundle 中,然后在我的 Activity 的 newInstance 方法中傳遞 ArrayList (這是從 SQLite 數據庫讀取的數據)后,我將它返回到我的 OnCreateView 中。

這部分有效,因為我在 Fragment 中正確顯示了我的數據。

我實現了一個從表中刪除所有數據的按鈕,現在我想在清理表后更新我的視圖。 刪除所有按鈕在我的主要活動中處理,我調用我的數據庫處理程序來清空表。

最好的方法是什么? 以下是與我相關的代碼部分:

我的片段 class:

public class MainFragment extends Fragment {

    public static final String RECETTES_KEY = "recettes_key";
    private List<Recette> mRecettes;
    private ListView mListView;

    public MainFragment() {
        // Required empty public constructor
    }

    public static MainFragment newInstance(List<Recette> r) {
        MainFragment fragment = new MainFragment();
        Bundle bundle = new Bundle();
        bundle.putParcelableArrayList(RECETTES_KEY, (ArrayList<? extends Parcelable>) r);
        fragment.setArguments(bundle);

        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mRecettes = getArguments().getParcelableArrayList(RECETTES_KEY);
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_main, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        configureListView();
    }

    // Configure ListView
    private void configureListView(){
        this.mListView = getView().findViewById(R.id.activity_main_list_view);
        RecetteAdapter adapter = new RecetteAdapter(getContext(), mRecettes);
        mListView.setAdapter(adapter);
    }
}

我的主要活動中的相關部分:這是在我的 OnCreate 方法中:

mDatabaseHandler = new DatabaseHandler(this);
mRecettes = mDatabaseHandler.readRecettes();
mDatabaseHandler.close();

這是我用來顯示片段的方法:

if (this.mMainFragment == null) this.mMainFragment = MainFragment.newInstance(mRecettes);
this.startTransactionFragment(this.mMainFragment);

如果我應該添加更多代碼,請告訴我,這是我第一次發帖:) Lucile

在您的R.layout.fragment_main中,您可以將 id 添加到根視圖,例如android:id@+id/fragment_root

每當您想更改片段視圖時:

活動中:

MainFragment fragment = (MainFragment) getSupportFragmentManager().getFragmentById(R.id.fragment_root);
fragment.updateList(mRecettes);

然后在MainFragment中創建新方法updateList()

public void updateList(List<Recette> recettes) {
    mRecettes.clear();
    mRecettes.addAll(recettes);
    configureListView();
}

您還可以在將片段添加到事務而不是使用其 ID 時標記片段,然后使用getSupportFragmentManager().getFragmentByTag()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM