I am searching for hours again and did not find an answer I understood/was looking for.
I habe an preference screen, that opens when the user clicks settings in the menu. This works. But how do I best enable the user to close this screen, when he is finished setting up.
I like the way it is done in Chrome, where you can return to the previous screen.
Other possibilities are appreciated as well.
Activity, which falls the preference (to which it should return):
public class MainActivity extends Activity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void startGame(View view)
{
Intent intent = new Intent(this, Game.class);
startActivity(intent);
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.layout.game_settings, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.action_settings:
getFragmentManager().beginTransaction()
.replace(android.R.id.content, new SettingsFragment())
.commit();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
Preferences:
public class SettingsFragment extends PreferenceFragment
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.layout.preferences);
}
}
XML:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android" >
<PreferenceCategory android:title="@string/game_settings">
<ListPreference
android:title="@string/circle_setting_title"
android:key="circle_setting"
android:summary="@string/circle_setting_summary"
android:entries="@array/circle_setting_amount"
android:entryValues="@array/circle_setting_amount_value"
android:defaultValue="3"/>
<ListPreference
android:title="@string/color_setting_title"
android:key="color_setting"
android:summary="@string/color_setting_summary"
android:entries="@array/color_setting_amount"
android:entryValues="@array/color_setting_amount_value"
android:defaultValue="3"/>
</PreferenceCategory>
</PreferenceScreen>
To make MainActivity the parent Activity of Preferences:
Assuming you already have your prefs.xml (or whatever you like to name it) file in your res/xml folder:
Declare your activities in your Manifest (in the application section):
<!-- Main activity -->
<activity
android:name="com.example.app.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- Preferences -->
<activity
android:name="com.example.app.PrefsActivity"
/>
Then, assuming you have a menu, a button, or whatever you'd like to show your PreferenceScreen with, just add this line to the event handler:
startActivity(new Intent(this, PrefsActivity.class));