目的:我要在软件中动态的选择组件背景,系统皮肤,自定义吐司背景等。
实现思路:要用到安卓中的SharedPrefence的功能,在设置里面写一个控件,设置一个点击监听器,点击的时候显示一个Alert选择弹窗,让你进行选择,对这个弹窗再设置一个点击监听器(onItemListener),点击到具体某个的时候,把对应的点击id保存到sahredprefence里面去,这样,其他地方就可以从这里取得设置里选择的值,进行动态个性化处理。
具体代码:
设置选择的操作:
scv_setAddressBg.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
int which = sp.getInt("which", 0);
final String[] items = {"半透明","活力橙","卫士蓝","金属灰","苹果绿"};
AlertDialog.Builder builder = new Builder(SettingActivity.this);
builder.setTitle("设置归属地显示背景");
builder.setSingleChoiceItems(items, which, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Editor edit = sp.edit();
edit.putInt("which", which);
edit.commit();
scv_setAddressBg.setDesc(items[which]);
dialog.dismiss();
}
});
builder.setNegativeButton("取消", null);
builder.show();
}
});
显示自定义吐司的操作:
public void showMyToast(String address) {
int[] ids = {R.drawable.call_locate_white,R.drawable.call_locate_orange,R.drawable.call_locate_blue,R.drawable.call_locate_gray,R.drawable.call_locate_green};
SharedPreferences sp = getSharedPreferences("config", MODE_PRIVATE);
int which = sp.getInt("which", 1);
view = View.inflate(this, R.layout.address_show, null);
TextView textView = (TextView) view.findViewById(R.id.tv_address);
textView.setText(address);
view.setBackgroundResource(ids[which]);
WindowManager.LayoutParams params = new WindowManager.LayoutParams();
params.height = WindowManager.LayoutParams.WRAP_CONTENT;
params.width = WindowManager.LayoutParams.WRAP_CONTENT;
params.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE|WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
params.format = PixelFormat.TRANSLUCENT;
params.type = WindowManager.LayoutParams.TYPE_TOAST;
wm.addView(view, params);
}
总结:
1.要注意数组的应用,ids[ value]这种使用方式要能想到用,将图片资源文件写在一个ids数组里是个很好的方式和想法。
2.细心,获得sp的时候名字写错了,config写成了congig。
3.理解调试技巧是靠经验和逻辑推理的,都很重要。