簡體   English   中英

刷新或重繪片段視圖

[英]Refresh or redraw Fragment's View

我到處搜索,但無法找到解決該問題的方法。 我正在顯示一個片段,當您按下按鈕時,它會在其上方打開一個新的活動。 然后,當該活動完成時,它將一些意圖數據返回給“片段/父項”活動。 該數據有時會更改TextView或向Fragment添加一個按鈕。 但是,如果不將Fragment重新添加到Backstack(popBackStack然后替換或添加),就無法獲取Fragment的視圖進行更新。

我嘗試過的幾件事是在Fragment的基本布局上調用invalidate()requestLayout() ,但是刷新視圖的唯一方法似乎是通過刪除並重新添加它再次調用onCreateView() 有沒有一種方法可以指定片段的“內容視圖”而無需重新加載它?

家長活動代碼:

// Used to retrieve the data from the first Activity
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == Activity.RESULT_OK) {
        // Try to update the Fragment's view here
        mMyFragment.refreshView(data.getString(NEW_BUTTON_TEXT));
    }
}

片段代碼(MyFragment):

private View mBaseLayout;

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    mBaseLayout = inflater.inflate(R.layout.my_layout, container, false);
    ...
    return mBaseLayout;
}

public void refreshView(String newButtonText) {
    Button button = mBaseLayout.findViewById(R.id.new_button);
    button.setText(newButtonText);
    button.setVisibility(View.VISIBLE);
    // TODO Reset the Fragment's view with the update mBaseLayout view
    // ? ? ?
    // Tried mBaseLayout.invalidate() and mBaseLayout.requestLayout() here 
}

對此有任何想法將非常有幫助,謝謝!

由於似乎沒有一種方法可以強制刷新Fragment的視圖,所以我最終只是分離並重新附加了片段,因此再次調用了onCreateView() 這似乎按我想要的方式工作。 我以此解決方案為起點,但需要添加commitAllowingStateLoss()來防止崩潰: https : commitAllowingStateLoss() 在這里允許狀態丟失是很好的,因為Fragment僅被重用並且數據仍然包含在其中。

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == Activity.RESULT_OK) {
        myFragment.updateData(data.getString(NEW_BUTTON_TEXT));
        // Need to use commitAllowingStateLoss() to prevent an IllegalStateException 
        // from being thrown
        getSupportFragmentManager()
            .beginTransaction()
            .detach(mContactDetailsFragment)
            .attach(mContactDetailsFragment)
            .commitAllowingStateLoss();
    }
}
Is there a way to specify the Fragment's "content view" without reloading it?

不,那是因為每次活動更改時都會重新繪制片段,因此當您打開並完成一個活動時,oncreateView上的片段將被調用,從而每次都將其重新繪制。

解:

您可以將片段作為活動的內部類 ,並在onActivityResult設置FLAG以檢查是否需要刷新。

if (resultCode == Activity.RESULT_OK) {
    isRefresh = true;
    stringData = data.getString(NEW_BUTTON_TEXT));
}

當片段的onCreateView被調用時

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mBaseLayout = inflater.inflate(R.layout.my_layout, container, false);
...
if(isRefresh)
   refreshView(stringData)
return mBaseLayout;
}

暫無
暫無

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

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