【问题标题】:How to change theme of an app on runtime using onCreateView instead of onCreate如何使用 onCreateView 而不是 onCreate 在运行时更改应用程序的主题
【发布时间】:2017-04-17 08:28:56
【问题描述】:

所以我现在有这个代码来更改我的应用程序的主题 -

public class SettingsActivity extends AppCompatActivity{
public static int themeCheck = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (themeCheck == 1){
        setTheme(R.style.Dark);
    }
    else{
        setTheme(R.style.Light);
    }
    setContentView(R.layout.fragment_settings);
    }
    // some other code changing other stuff

我正在和我班上的另外一个人一起做这个项目,他正在制作实际的骨架代码,结果他使用了片段并且没有将活动扩展到 AppCompat。所以,我必须合并我的代码的类看起来像这样 -

public class SettingsFrament extends android.support.v4.app.Fragment 
implements MainActivityFragment {
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
Bundle savedInstanceState) {
    View rootView = localInflater.inflate(R.layout.fragment_settings, 
    container, false);
    getActivity().setTitle(getString(R.string.settings_fragment_title));
    return rootView;

//This rootView and other bits that that guy gave me is redirecting the app 
//to my activity from the menu bar that he has.

我想知道如何将我的代码与这个类合并。 (我不用合并,可以把代码写下来,只是不知道onCreateView中setTheme等方法怎么用。)

任何帮助将不胜感激。

【问题讨论】:

  • 你试过getActivity().setTheme()吗?你必须重新开始活动
  • 也检查this

标签: java android android-fragments android-theme appcompatactivity


【解决方案1】:

在 onCreateView 回调中试试这个。

    final Context theme1 = new ContextThemeWrapper(getActivity(), R.style.yourCustomTheme1);
    final Context theme2 = new ContextThemeWrapper(getActivity(), R.style.yourCustomTheme2);

    LayoutInflater localInflater;

    getActivity().setTitle(getString(R.string.settings_fragment_title));

    if (themeCheck == 1){
         localInflater = inflater.cloneInContext(theme1);
    }
    else{
         localInflater = inflater.cloneInContext(theme2);
    }

    View rootView = localInflater.inflate(R.layout.fragment_settings,
            container, false);

    return rootView;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-17
    • 1970-01-01
    • 2020-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多