Android给应用定制皮肤
jopen
11年前
在实现程序功能的同时,如果能让程序界面更加美观,有锦上添花之妙.
先说思路:
1)皮肤也就是相关的资源文件单独放置在某个工程中,一种皮肤一个工程文件.一个工程包括N多的资源文件,多个工程间资源的关系是,文件名,资源ID等完全一样.不同的可能是图片资源,style等的设置不一样.
皮肤工程在AndroidManifest.xml中配置android:sharedUserId="com.eric.skinmain".
表明允许com.eric.skinmain访问本工程中的资源文件. com.eric.skinmain是主项目的包名
3)主项目通过 this.createPackageContext("com.eric.blackskin",Context.CONTEXT_IGNORE_SECURITY);
获取到com.eric.blackskin对应的Context,然后通过返回的context对象就可以访问到com.eric.blackskin中的任何资源,如同访问自身的资源一样.
注:记得先安装皮肤工程对应的apk文件.
public class main extends Activity { /** Called when the activity is first created. */ private LinearLayout showBg; private Button btn; private Context green_skin_Context = null; private Context black_skin_Context = null; int flag = 0; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); showBg = (LinearLayout) findViewById(R.id.linear_layout_1); try { green_skin_Context = this.createPackageContext( "com.eric.greenskin", Context.CONTEXT_IGNORE_SECURITY); } catch (NameNotFoundException e) { e.printStackTrace(); } try { black_skin_Context = this.createPackageContext( "com.eric.blackskin", Context.CONTEXT_IGNORE_SECURITY); } catch (NameNotFoundException e) { e.printStackTrace(); } btn = (Button) findViewById(R.id.btn_change_skin); btn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (flag == 0) { showBg.setBackgroundDrawable(green_skin_Context .getResources().getDrawable(R.drawable.bg)); btn.setBackgroundDrawable(green_skin_Context .getResources().getDrawable(R.drawable.btn_normal)); flag = 1; } else if (flag == 1) { showBg.setBackgroundDrawable(black_skin_Context .getResources().getDrawable(R.drawable.bg)); btn.setBackgroundDrawable(black_skin_Context .getResources().getDrawable(R.drawable.btn_normal)); flag = 0; } } }); } }