滑动即可刷新问题

时间:2019-01-27 20:24:03

标签: android android-fragments swiperefreshlayout

我将hide片段添加到第一个片段,然后显示第二个片段,没有任何问题,但是现在当我使用滑动刷新应用程序崩溃时。.pleeeease帮助我解决此问题。

使用此代码隐藏第一个片段iam:

public void replaceFragment(Fragment someFragment,String tag){

FragmentManager fm = getFragmentManager();
Fragment fragment = fm.findFragmentByTag(tag);
Fragment fragment2 = fm.findFragmentById(R.id.frameContainer);

if (fragment != fragment2) {
    FragmentTransaction transaction = getFragmentManager().beginTransaction();
    transaction.setCustomAnimations(R.anim.right_enter, R.anim.left_out, R.anim.left_enter, R.anim.right_out);
    transaction.hide(fragment2);
    transaction.add(R.id.frameContainer,someFragment);
    transaction.addToBackStack(tag);
    transaction.commit();
}

,并使用以下代码在“活动”中滑动刷新:

 private void swipe_swipeRefresh() {
        String fragment = null;
        swipeRefreshLayout.setRefreshing(true);
        Fragment currentFragment = getSupportFragmentManager().findFragmentById(R.id.frameContainer);
        if (currentFragment instanceof FragmentHome) {
            fragment = "FragmentHome";
            }
        if (currentFragment instanceof BlogFragment) {
            fragment = "BlogFragment";
        }
      Handler handler = new Handler();
        final String finalFragment = null;
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                SettingsMain.reload(HomeActivity.this, finalFragment);
                swipeRefreshLayout.setRefreshing(false);
             SettingsMain.hideDilog();
            }
        }, 2000);
    }

SettingsMain.reload(HomeActivity.this,finalFragment);这条线来自:

  public static void reload(Context context, String tag) {
        Fragment frg;
        FragmentManager manager = ((AppCompatActivity) context).getSupportFragmentManager();

        frg = manager.findFragmentByTag(tag);
        final FragmentTransaction ft = manager.beginTransaction();

      ft.detach(frg);
      ft.attach(frg);
      ft.commit();
    }

1 个答案:

答案 0 :(得分:0)

请注意,由于以下原因,您的代码中finalFragment中的SettingsMain.reload(HomeActivity.this, finalFragment);null

    final String finalFragment = null;

接下来,在reload()方法frg = manager.findFragmentByTag(tag);内部使用。但是这里的tag为空,因此找不到该片段。结果frgnull。拆卸并附加它会导致崩溃,因为frgnull

要修复此问题,请尝试将行更改为

final String finalFragment = fragment;