简体   繁体   中英

Android: Close activity from PreferenceFragment

my application is running just in background. As activity I have just Settings and, after pressing Start button, a service is called and activity is finished. In order to this I'm using MainActivity who call PreferenceFragment:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getFragmentManager().beginTransaction().replace(android.R.id.content, new MainSettingsFragment()).commit();
}

In order to start Service or exit from activity I've created a menu

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_settings, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) { 
    case R.id.action_exit:
        finish();
        break;
    case R.id.action_start:
        Intent intentService = new Intent(MainSettingsActivity.this, ReminderService.class);
        startService(intentService);
        finish();
        break;
    return true;
}

This is my very simple PreferenceFragment, used to show settings_layout

public class MainSettingsFragment extends PreferenceFragment{

     @Override
     public void onCreate(Bundle savedInstanceState){
         super.onCreate(savedInstanceState);
         addPreferencesFromResource(R.xml.settings_layout);
     }
}

In settings_layout is also defined two Preference item: Start and Exit.

I would like to move functions Start and Exit placed in menu, as item in layout. It's easy to create an intent in xml file letting start the service, but I don't know how to close the activity. How can I implement finish() function inside of Activity (who call PreferenceFragment) in order to kill her self? How can I get the event "Press Exit" inside of Activity? Getting the event inside PreferenceFragment is enough to implement a listener, like:

@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPref, String key) {
    Preference pref = findPreference(key);
    /* Do something */
    } 
}

but after that I have no idea how to close the activity. Any Idea? Many thanks!

IF I get this correct you would like to close the activity from a fragment? Why don't you use getActivity() in your fragment and then call finish()?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM