android新手,目前在整在一个android需求,需要集成媒体播放器, 在菜单中添加一个checkbox,当选中checkbox的时候停止播放器,当取消选中的时候启动播放器,目前我已经实现了选中checkbox停止播放器。
当我 取消选中checkbox的时候,报错了,找了好久没找到啥原因.心情很不好.....
我的代码如下:
MainActivity
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
@Override
public
boolean
onOptionsItemSelected(MenuItem item)
{
switch
(item.getItemId())
{
case
R.id.action_help:
Intent
intent = new
Intent(MainActivity1.
this ,
help. class );
startActivity(intent);
return
true
;
case
R.id.music:
final
CheckBox music = (CheckBox)findViewById(R.id.music);
music.setChecked( true );
music.setOnClickListener( new
OnClickListener(){
public
void
onClick(View v){
if
(((CheckBox) v).isChecked()) {
backsound
= MediaPlayer.create(MainActivity1. this ,
R.raw.backsound);
backsound.start();
backsound.setLooping( true );
} else {
music.setChecked( false );
backsound.stop();
}
}});
default :
return
super
.onOptionsItemSelected(item);
}}}
|
Main_activity.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
< menu xmlns:android = "http://schemas.android.com/apk/res/android" >
< item
android:id = "@+id/action_settings"
android:orderInCategory = "100"
android:showAsAction = "never"
android:title = "@string/action_settings" />
< item
android:id = "@+id/action_help"
android:orderInCategory = "100"
android:showAsAction = "never"
android:title = "@string/help" />
< item
android:id = "@+id/music"
android:title = "@string/musik"
android:checkable = "true"
android:checked = "true" />
|
处理方法
1
|
< preferencescreen
xmlns:android
= "http://schemas.android.com/apk/res/android" >
< preferencecategory
android:title
= "@string/title_category"
android:summary
= "@string/summary_category" >
< checkboxpreference
android:title
= "@string/title_main"
android:summary
= "@string/summary_main"
android:defaultvalue
= "true"
android:key
= "main" >
</ checkboxpreference ></ preferencecategory >
</ preferencescreen >
|
你选在只需要通过简单设置 setting android:dependancy 就能够实现这个功能,现在在res目录创建一个xml文件,放入上面xml代码,然后执行如下操作
1
2
3
4
5
6
7
8
9
10
11
|
public
class
SettingsActivity
extends
PreferenceActivity {
@Override
protected
void
onCreate(Bundle savedInstanceState) {
super .onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
}
|
当然,你也可以通过其他的方式完成,比如 fragments ,不过这种方式更简单些
原文地址:http://www.itmmd.com/201411/156.html
该文章由 萌萌的IT人 整理发布,转载须标明出处。