onBackPressed并调用刷新功能Android

时间:2018-07-05 04:49:21

标签: java android android-fragments

当我按下后退按钮时,我只想刷新选项卡栏活动中的一个片段。我该如何实现?我尝试过的

  

java.lang.NullPointerException:尝试调用虚拟方法   'android.support.v4.app.FragmentTransaction   android.support.v4.app.FragmentManager.beginTransaction()'为null   对象引用

片段配置文件

public void refreshFragment(){
    FragmentTransaction ft = getFragmentManager().beginTransaction();
    ft.detach(this).attach(this).commit();
}

编辑个人资料活动

@Override
public void onBackPressed() {
    super.onBackPressed();
    FragmentProfile fragment = new FragmentProfile();
    fragment.refreshFragment();
}

3 个答案:

答案 0 :(得分:3)

尽管它是常规的java.lang.NullPointerException:,但我想在此阐明一些原因。
1. super.onBackPressed();finish() Activity FragmentManager,因此您无法在其BackStack上进行任何事务。

2.您要刷新片段,然后应该从FragmentProfile fragment = new FragmentProfile(); 获取当前片段以刷新它。

Fragment

这将为您提供一个尚未附加的新FragmentTransaction,并且对其进行任何调用都没有任何意义。这是因为getActivity()为空,而对于新的Fragment getFragmentManager()也将为空的原因。

根据定义,原因FragmentManager返回Activity中的 @Override public void onBackPressed() { if(SomeCondition) { FragmentProfile fragment = //Get the Fragment from Fragment Manager Here fragment.refreshFragment(); }else { super.onBackPressed(); } } 。而且您的新Fragment尚未附加,因此它将返回null。

  

getFragmentManager()   返回用于与与此片段活动相关联的片段进行交互的FragmentManager。

因此您的代码应如下所示。

onBackPressed()

我在Activity中添加了一个条件,因为您不想完全禁用“后退”按钮。如果您将布局用作片段的容器,则可以通过遵循getSupportFragmentManager().findFragmentById(); getSupportFragmentManager().findFragmentByTag(); 中的两种方法来获取片段。

startActivityForResult();

编辑:-问题不够明确。 OP想要实现的目标只需使用apply plugin: 'com.android.application' android { compileSdkVersion 27 buildToolsVersion '27.0.2' defaultConfig { applicationId "com.casperon.app.rydepass" minSdkVersion 18 targetSdkVersion 27 versionCode 17 versionName "4.2" multiDexEnabled true } aaptOptions { cruncherEnabled = false } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } dexOptions { javaMaxHeapSize "4g" } aaptOptions.cruncherEnabled = false aaptOptions.useNewCruncher = false useLibrary 'org.apache.http.legacy' } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) compile project(':slideDateTimePicker') compile project(':CountryCodePicker') compile 'com.android.support:appcompat-v7:27.0.2' compile 'com.android.support:multidex:1.0.3' compile 'com.prolificinteractive:material-calendarview:1.4.3' compile 'com.mcxiaoke.volley:library:1.0.19' compile 'com.github.ybq:Android-SpinKit:1.1.0' compile 'com.squareup:android-times-square:1.6.5@aar' compile 'com.google.android.gms:play-services:11.0.0' compile 'com.android.support:cardview-v7:24.0.0' compile 'com.squareup.picasso:picasso:2.5.2' compile 'com.github.d-max:spots-dialog:0.7@aar' compile 'com.android.support:support-annotations:24.2.0' compile 'com.balysv:material-ripple:1.0.2' compile 'com.github.paolorotolo:expandableheightlistview:1.0.0' compile 'com.github.ganfra:material-spinner:1.1.0' compile 'com.baoyz.swipemenulistview:library:1.3.0' compile 'com.googlecode.libphonenumber:libphonenumber:8.7.0' compile 'com.github.jakob-grabner:Circle-Progress-View:v1.2.2' compile 'me.drakeet.materialdialog:library:1.2.2' compile 'com.wang.avi:library:1.0.1' compile 'com.android.support:design:24.2.1' compile 'com.nineoldandroids:library:2.4.0' compile 'org.igniterealtime.smack:smack-android:4.1.0-rc1' compile 'org.igniterealtime.smack:smack-tcp:4.1.0-rc1' compile 'org.igniterealtime.smack:smack-im:4.1.0-rc1' compile 'org.igniterealtime.smack:smack-extensions:4.1.0-rc1' compile 'net.hockeyapp.android:HockeySDK:3.5.0' compile 'pl.droidsonroids.gif:android-gif-drawable:1.1.+' compile 'org.jsoup:jsoup:1.8.3' compile 'com.android.support:multidex:1.0.1' compile 'com.github.crazy1235:RichEditText:v2.0' compile 'com.android.support.constraint:constraint-layout:+' compile 'org.apache.httpcomponents:httpcore:4.4.1' compile 'com.squareup:android-times-square:1.6.5@aar' compile 'org.apache.httpcomponents:httpclient:4.5' 即可完成。请参阅How to manage startActivityForResult on Android?

答案 1 :(得分:1)

您需要在onBackPressed()内部更改顺序。将super.onBackPressed();移动到函数末尾。检查以下内容:

当前为:

@Override
public void onBackPressed() {
    super.onBackPressed();
    FragmentProfile fragment = new FragmentProfile();
    fragment.refreshFragment();
}

更改为:

@Override
public void onBackPressed() {
    FragmentProfile fragment = new FragmentProfile();
    fragment.refreshFragment();
    super.onBackPressed();
}

还对refreshFragment()方法进行以下更改。通过Fragment获取要刷新的TAG

public void refreshFragment(){
    Fragment fragment = null;
    fragment = getSupportFragmentManager().findFragmentByTag("Fragment_TAG_You_want_to_refresh");
    final FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
    fragmentTransaction.detach(fragment).attach(fragment).commit();
}

检查here,了解如何向片段添加唯一标记。

答案 2 :(得分:1)

您可以使用 SharedPreferences 来做到这一点。

第1步:创建一个常量类。

public class Constants {
    public static final String REFRESH = "refresh_content";
}

第2步:将boolean放入常量。在“编辑配置文件活动”中刷新

private SharedPreferences pref;

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
    pref = PreferenceManager.getDefaultSharedPreferences(getContext());

    return inflater.inflate(R.layout.fragment_rostering, container, false);
}

public void onBackPressed() {
    SharedPreferences.Editor editor = pref.edit();
    editor.putBoolean(Constants.REFRESH, true);
    editor.commit();
    super.onBackPressed();
}

步骤3:在Fragment Profile的onResume上调用刷新功能

private SharedPreferences pref;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    pref = PreferenceManager.getDefaultSharedPreferences(getContext());

    return inflater.inflate(R.layout.fragment_profile, container, false);
}

@Override
public void onResume() {
    super.onResume();
    if(pref.getBoolean(Constants.REFRESH, false)){
        SharedPreferences.Editor editor = pref.edit();
        editor.putBoolean(Constants.REFRESH, false);
        editor.commit();
        refreshFragment();
    }
}