我正在学习根据 this tutorial 设计应用程序主题
首先,在AndroidManifest中,我使用了
<activity android:theme="@android:style/MyTheme">
然后我得到的结果显示 UI 线程必须做太多工作,因此它跳过了一些帧。然后我考虑以编程方式设置主题 通过使用 Thread 但它也不起作用。
我的自定义主题
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="MyTheme"
parent="android:Theme.Material" >
<item name="android:colorPrimary">#FF0000</item>
</style>
我的主要 Activity xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.material_theme.MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:gravity="center"
android:textSize="30sp"
android:text="@string/hello_world" />
</RelativeLayout>
我的java代码
package com.example.material_theme;
import android.app.Activity;
import android.os.Bundle;
import android.os.SystemClock;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new Thread(new Runnable() {
@Override
public void run() {
SystemClock.sleep(100);
setTheme(R.style.MyTheme);
}
}).start();
setContentView(R.layout.activity_main);
}
}
最佳答案
您只能在setContentView
之前设置主题。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTheme(R.style.MyTheme);
setContentView(R.layout.activity_main);
}
根据您的情况,您可能需要使用此代码
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new Handler().postDelayed(new Runnable(){
@Override
public void run(){
setTheme(R.style.MyTheme);
setContentView(R.layout.activity_main);
}
}, 100);
setContentView(R.layout.activity_main);
}
PS:在这种情况下您不需要多线程。所有的事情都可以在主线程中完成。
关于java - setTheme(R.style.MyTheme) 不适用于线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32645253/