简体   繁体   English

Android:从PreferenceFragment关闭活动

[英]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: 为此,我使用的是调用PreferenceFragment的MainActivity:

@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 这是我非常简单的PreferenceFragment,用于显示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. 在settings_layout中还定义了两个首选项:开始和退出。

I would like to move functions Start and Exit placed in menu, as item in layout. 我想在菜单中移动函数Start和Exit,作为布局中的项目。 It's easy to create an intent in xml file letting start the service, but I don't know how to close the activity. 在xml文件中创建一个意图很容易启动服务,但我不知道如何关闭活动。 How can I implement finish() function inside of Activity (who call PreferenceFragment) in order to kill her self? 如何在Activity(调用PreferenceFragment)中实现finish()函数以杀死她自己? How can I get the event "Press Exit" inside of Activity? 如何在活动中获得“按退出”活动? Getting the event inside PreferenceFragment is enough to implement a listener, like: 在PreferenceFragment中获取事件足以实现一个侦听器,如:

@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()? 为什么不在片段中使用getActivity()然后调用finish()?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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