1. 程式人生 > >Android動態載入——載入已安裝APK中的類

Android動態載入——載入已安裝APK中的類

public class TestAActivity extends Activity {
 
    /** TestB包名 */
    private static final String PACKAGE_TEST_B = "com.nmbb.b";
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        try {
            
final Context ctxTestB = getTestBContext(); Resources res = ctxTestB.getResources(); // 獲取字串string String hello = res.getString(getId(res, "string", "hello")); ((TextView) findViewById(R.id.testb_string)).setText(hello); // 獲取圖片Drawable Drawable drawable = res .getDrawable(getId(res,
"drawable", "testb")); ((ImageView) findViewById(R.id.testb_drawable)) .setImageDrawable(drawable); // 獲取顏色值 int color = res.getColor(getId(res, "color", "white")); ((TextView) findViewById(R.id.testb_color)) .setBackgroundColor(color);
// 獲取佈局檔案 View view = getView(ctxTestB, getId(res, "layout", "main")); LinearLayout layout = (LinearLayout) findViewById(R.id.testb_layout); layout.addView(view); // 啟動TestB Activity findViewById(R.id.testb_activity).setOnClickListener( new OnClickListener() { @Override public void onClick(View v) { try { @SuppressWarnings("rawtypes") Class cls = ctxTestB.getClassLoader() .loadClass("com.nmbb.TestBActivity"); startActivity(new Intent(ctxTestB, cls)); } catch (ClassNotFoundException e) { e.printStackTrace(); } } }); } catch (NameNotFoundException e) { e.printStackTrace(); } } /** * 獲取資源對應的編號 * * @param testb * @param resName * @param resType * layout、drawable、string * @return */ private int getId(Resources testb, String resType, String resName) { return testb.getIdentifier(resName, resType, PACKAGE_TEST_B); } /** * 獲取檢視 * * @param ctx * @param id * @return */ public View getView(Context ctx, int id) { return ((LayoutInflater) ctx .getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(id, null); } /** * 獲取TestB的Context * * @return * @throws NameNotFoundException */ private Context getTestBContext() throws NameNotFoundException { return createPackageContext(PACKAGE_TEST_B, Context.CONTEXT_IGNORE_SECURITY | Context.CONTEXT_INCLUDE_CODE); }