以前寫過一個關於皮膚的換膚思路的博客。但那個裏邊主要是針對於資源換膚,沒有佈局換膚的概念。今天實現了一個可以更換佈局的換膚實現。
思路還是上篇文章的思路,只是做了一個簡單的實現。
代碼如下:
package com.test.android.skin.main;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView((View)getResource("main", "layout"));
Button btn = (Button) findViewById(R.id.btn);
btn.setBackgroundDrawable((Drawable) getResource("btn_background", "drawable"));
SqLHelper helper = new SqLHelper(this);
SQLiteDatabase db = helper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("id", "3");
values.put("packname", "org.yangzc.package3");
db.insert("skinTab", null, values);
db.close();
db = helper.getWritableDatabase();
Cursor c = db.rawQuery("select * from skinTab", null);
while(c.moveToNext()){
String id = c.getString(c.getColumnIndex("id"));
String packname = c.getString(c.getColumnIndex("packname"));
Log.d("Tag", "Id:"+id + " packname:" + packname);
}
}
private Object getResource(String filename, String defType){
Context myContext = null;
try {
myContext = this.createPackageContext(
"com.test.android.skin.myskin",
Context.CONTEXT_IGNORE_SECURITY);
int id = myContext.getResources().getIdentifier(filename, defType, myContext.getPackageName());
if("drawable".equals(defType)){
return myContext.getResources().getDrawable(id);
}else if("layout".equals(defType)){
LayoutInflater inflater = (LayoutInflater) myContext.getSystemService(LAYOUT_INFLATER_SERVICE);
return inflater.inflate(id, null);
}
} catch (NameNotFoundException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
}
方向一:
這幾天看了一下源碼,主要是關於Context的東西。理想化的情況是,進入activity之後首先改一下context,這樣之後框架就會動態實現換膚功能。追到了ContextThemeWrapper類,本來看到了attachBaseContext方法,以爲OK了呢。看到一下代碼鬱悶了。繼續看...
protected void attachBaseContext(Context base) {
if (mBase != null) {
throw new IllegalStateException("Base context already set");
}
mBase = base;
}