Android之使用RatingBar设置游戏难度并保存
最近在学习游戏开发,在游戏中常常需要设置游戏的难度,在Android中我们可以使用RatingBar来实现。具体看下面的代码:
效果图如下:
package com.cloay.pt.ui;
import java.io.FileNotFoundException;
import java.io.IOException;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.RatingBar.OnRatingBarChangeListener;
import android.widget.TextView;
import com.cloay.pt.BasicActivity;
import com.cloay.pt.R;
import com.cloay.pt.constants.Constant;
import com.cloay.pt.utils.ImageUtil;
/**
* 游戏设置类,游戏难度等
* @author Cloay
* 2011-12-23
* 下午05:21:41
*/
public class SettingsActivity extends BasicActivity{
private SharedPreferences settings; //保存设置
private RatingBar ratingBar;
private TextView defaultPicture;
private TextView picture;
private ImageView previewImage;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings);
BasicActivity.allActivity.add(this);
//初始化数据
initData();
}
/**
* 初始化数据
*/
private void initData() {
settings = getSharedPreferences("settings", 0);
ratingBar = (RatingBar) findViewById(R.id.rating);
//游戏默认图片
defaultPicture = (TextView) findViewById(R.id.def);
//从图库中选择图片,自定义
picture = (TextView) findViewById(R.id.picture);
previewImage = (ImageView)findViewById(R.id.preview);
if("".equals(settings.getString("picture", ""))) {
previewImage.setImageResource(R.drawable.def);
}else{
previewImage.setImageBitmap(ImageUtil.getBitmapFromSDCard(settings.getString("picture", "")));
}
//设置难度选择监听
ratingBar.setOnRatingBarChangeListener(new OnRatingBarChangeListener() {
@Override
public void onRatingChanged(RatingBar ratingBar, float rating,
boolean fromUser) {
settings.edit().putInt("level", (int)rating).commit(); //保存用户设置后的游戏难度
showToast(SettingsActivity.this, (int)rating);
}
});
//设置图片选择监听
defaultPicture.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
settings.edit().putString("picture", "").commit();
previewImage.setImageResource(R.drawable.def);
}
});
picture.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
/* 开启Pictures画面Type设定为image */
intent.setType("image/*");
/* 使用Intent.ACTION_GET_CONTENT这个Action */
intent.setAction(Intent.ACTION_GET_CONTENT);
/* 取得相片后返回本画面 */
startActivityForResult(intent, 1);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
Uri uri = data.getData();
ContentResolver cr = this.getContentResolver();
try { &n
补充:移动开发 , Android ,