Android实现动态切换组件背景的方法

时间:2022-01-28 08:00:21

本文所述的程序实现的功能为在软件中动态的选择组件背景,系统皮肤,自定义吐司背景等。
为实现这一要求,就需要用到安卓中的SharedPrefence的功能,首先在设置里面写一个控件,设置一个点击监听器,点击的时候显示一个Alert选择弹窗,让你进行选择,对这个弹窗再设置一个点击监听器(onItemListener),点击到具体某个的时候,把对应的点击id保存到sahredprefence里面去,这样,其他地方就可以从这里取得设置里选择的值,进行动态个性化处理。

具体代码如下:

1.设置选择的操作:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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();
      }
    });

2.显示自定义吐司的操作:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public void showMyToast(String address) {
    <span style="color:#ff6600;">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};</span>
    <span style="color:#ff6600;">SharedPreferences sp = getSharedPreferences("config", MODE_PRIVATE);
    int which = sp.getInt("which", 1);</span>
    view = View.inflate(this, R.layout.address_show, null);
    TextView textView = (TextView) view.findViewById(R.id.tv_address);
    textView.setText(address);
    <span style="color:#ff6600;">view.setBackgroundResource(ids[which]);</span>
     
    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);
  }

3.归纳总结如下:

(1)要注意数组的应用,ids[ value]这种使用方式要能想到用,将图片资源文件写在一个ids数组里是个很好的方式和想法。
(2)细心,获得sp的时候名字写错了,config写成了configs。
(3)理解调试技巧是靠经验和逻辑推理的,都很重要。