步骤1:在res/values/strings.xml定义菜单项要用到到的字符串资源,如:
<string name="settings_label">Settings...</string>
<string name="settings_title">Sudoku settings</string>
<string name="settings_shortcut">s</string>
<string name="music_title">Music</string>
<string name="music_summary">Play background music</string>
<string name="hints_title">Hints</string>
<string name="hints_summary">Show hints during play</string>
步骤2:在res/menu/menu.xml文件中定义菜单:
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/settings"
android:title="@string/settings_label"
android:alphabeticShortcut="@string/settings_shortcut"/>
</menu>
上面<item>定义了一个菜单项。
步骤3:接下来要修改项目类(Sudoku.java),将刚才定义的菜单加入到Sudoku类中:
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
// getMenuInflater()方法返回一个MenuInflater类的实例,用于从XML文件中读取菜单的定义,并将其转换为实际的视图
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
// 用户选择任何菜单时,将会调用onOptionsItemSelected()方法:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// return super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.settings:
startActivity(new Intent(this, com.shutao.sudoku.Settings.class));
return true;
}
return false;
}
步骤4:在res/xml/settings.xml中定义首选项:
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Android提供了方便的工具来定义所有的程序首选项,并支持在几乎不需要编写代码的情况显示这些首选项 -->
<CheckBoxPreference
android:key="music"
android:title="@string/music_title"
android:summary="@string/music_summary"
android:defaultValue="true"/>
<CheckBoxPreference
android:key="hints"
android:title="@string/hints_title"
android:summary="@string/hints_summary"
android:defaultValue="true"/>
</PreferenceScreen>
步骤5:接下来定义Setting类,它继承自PreferenceActivity类:
public class Settings extends PreferenceActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// addPreferencesFromResource()方法从XML文件中读取设置定义。
addPreferencesFromResource(R.xml.settings);
}
}
步骤6、不要忘了在AndroidManifest.xml文件中注册Settings活动:
<activity android:name=".Settings"
android:label="@string/settings_title">
</activity>