片段在点击时不会自动更新

时间:2016-10-17 04:12:47

标签: java android fragment refresh

我的操作栏中有一个片段,如果用户点击片段按钮,页面应该自动更新/刷新,如果有任何内容。我面临的问题是,片段第一次没有自动更新,但是当我第二次按下它时会更新和刷新。

这是流程:

选择片段1 - >没有更新/刷新 - >返回并从操作栏中选择另一个片段2 - >再次选择片段1 - >更新片段1的UI。

我在Async任务的onPostExecute中调用MainActivity中的片段1。

MainActivity,

private final FragmentOne f1 = new FragmentOne();

 @Override
        protected void onPostExecute(Object o) {
            super.onPostExecute(o);
            f1.updateUI();
        }

我的片段类中有这段代码。

// Updates the fragment-1 UI
public void updateUI() {
    if (isAdded()) {
        String currentDatabaseName = null;
        hideAllTables();
        hideWarningLabelsAndHeaders();
        progressBarIndicator.setVisibility(View.VISIBLE);

        if (null != getUserIdentifier()) {
            currentDatabaseName = Utils.buildUserDataFromFli(getUserIdentifier());
        }
        if (null != currentDatabaseName) {
            shopData = new ShopDao(ShopApplication.getLoggedInUser(), Utils.getDatabaseIndexMap());
            transcationData = new TranscationDao(ShopApplication.getLoggedInUser(), Utils.getDatabaseIndexMap());
        }
        configureUserDependentFetchers(getUserIdentifier());
    }
}

1 个答案:

答案 0 :(得分:2)

尝试这个,也许可以为你工作;)

活动:

@Override
    protected void onPostExecute(Object o) {
        super.onPostExecute(o);
        //to send broadcast for refresh
        Intent intentRefresh = new Intent("com.yourapp.REFRESH_DATA");
        LocalBroadcastManager.getInstance(YourActivity.this).sendBroadcast(intentRefresh);
    }

在你的片段上:

private final BroadcastReceiver broadcastReceiverMap = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (action.equals("com.yourapp.REFRESH_DATA")) {
           //put here code for refresh
        }
    }
};

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_one, container, false);

    //register your LocalBroadcatManager
    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction("com.yourapp.REFRESH_DATA");
    LocalBroadcastManager.getInstance(getActivity()).registerReceiver(
            broadcastReceiverMap, intentFilter);
    return view;
}