萬盛學電腦網

 萬盛學電腦網 >> 網絡編程 >> 安卓開發 >> Android中實現動態切換組件背景的操作

Android中實現動態切換組件背景的操作

 這個也是昨天學習用到的,總結下思路吧,因為這個知識點以後絕對會再次用到。

目的:我要在軟件中動態的選擇組件背景,系統皮膚,自定義吐司背景等。

實現思路:要用到安卓中的SharedPrefence的功能,在設置裡面寫一個控件,設置一個點擊監聽器,點擊的時候顯示一個Alert選擇彈窗,讓你進行選擇,對這個彈窗再設置一個點擊監聽器(onItemListener),點擊到具體某個的時候,把對應的點擊id保存到sahredprefence裡面去,這樣,其他地方就可以從這裡取得設置裡選擇的值,進行動態個性化處理。

 

具體代碼:

設置選擇的操作:

 

  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();             }         });

 

 

顯示自定義吐司的操作:

  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);     }



總結:

1.要注意數組的應用,ids[ value]這種使用方式要能想到用,將圖片資源文件寫在一個ids數組裡是個很好的方式和想法。

2.細心,獲得sp的時候名字寫錯了,config寫成了congig。

3.理解調試技巧是靠經驗和邏輯推理的,都很重要。

copyright © 萬盛學電腦網 all rights reserved