Android ::如何以编程方式从其他apk更改主题

Ron*_*tdu 10 android themes

我有一个名为:preference的应用程序,我想为这个应用程序制作主题.我的首选AndroidManifest.xml是:

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="com.example.preference.MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>        
</application>
Run Code Online (Sandbox Code Playgroud)

在MainActivity.java中:我收到了主题更改按钮,点击:

themeChange = (Button) findViewById(R.id.themeChange);
themeChange.setOnClickListener(this);
Run Code Online (Sandbox Code Playgroud)

我有一个主题应用程序,其中包含PinkTheme(styles.xml),包名称为com.example.theme.

<resources xmlns:android="http://schemas.android.com/apk/res/android">
    <style name="AppBaseTheme" parent="android:Theme.Light">
        <!--
            Theme customizations available in newer API levels can go in
            res/values-vXX/styles.xml, while customizations related to
            backward-compatibility can go here.
        -->
    </style>
    <style name="PinkTheme" parent="AppBaseTheme" >
        <item name="android:textColor">#FF69B4</item>
        <item name="android:typeface">monospace</item>
        <item name="android:textSize">40sp</item>
        <item name="android:windowBackground">#008000</item>
    </style>
</resources>
Run Code Online (Sandbox Code Playgroud)

我喜欢的onClick()是:

public void onClick(View v) {
    // TODO Auto-generated method stub
    switch(v.getId()){

    case R.id.themeChange:          
      Resources res = null;
      try {
          res = getPackageManager().getResourcesForApplication("com.example.theme");
      } catch (NameNotFoundException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
      }
      if(null != res) {
        int sId = res.getIdentifier("com.example.theme:style/PinkTheme", null, null);
        Theme themeObject = res.newTheme();  // theme object
        themeObject.applyStyle(sId, true);  // Place new attribute values into the theme
        getTheme().setTo(themeObject);
      }
        break;

    default:
        break;

    }
}
Run Code Online (Sandbox Code Playgroud)

我收到了主题包的主题对象,并尝试设置首选项应用程序的主题.但它不起作用.请帮助我:如何以编程方式将主题从其他应用程序设置到我当前的应用程序.

Jim*_*Jim 1

如果您想更改一个应用程序中另一个应用程序的设置,那么最简单的方法可能是将主题 ID 放入意图中,并将该意图发送到您的 MainActivity(或 IntentService),接收应用程序可以在其中处理数据。例如,当意图到达时,您可以像在“onClick”逻辑中处理单击事件一样处理它。

例如,应用程序可以创建如下意图:

    Intent intent = new Intent("android.intent.action.MAIN");
    intent.setComponent(new ComponentName("your.package", "your.package.component"));
    intent.putExtra("theme_id", "theme_1");
    startActivity(intent);
Run Code Online (Sandbox Code Playgroud)

然后在您的活动中,使用getIntent().getStringExtra("theme_id")将数据传递到您的应用程序。