Android:如何以编程方式将Activity的主题设置为Theme.Dialog

100*_*abh 37 android themes dialog android-activity

所以我有一个Activity(说TestActivity)需要作为一个正常的未经训练Activity以及Theme.Dialog在其他地方.我正在尝试TestActivity为这两个任务重用相同的内容.

我正在寻找动态设置主题.代码很简单:这是我的活动onCreate,它适用于黑色背景

public void onCreate(Bundle icicle) {
    if (Utility.isDialog == true)
        setTheme(android.R.style.Theme_Dialog);
    super.onCreate(icicle);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
.....
Run Code Online (Sandbox Code Playgroud)

这是Manifest Entry

<activity android:name=".TestActivity"/>
Run Code Online (Sandbox Code Playgroud)

在此期间,我发现一篇帖子说这里无法完成的帖子是http://code.google.com/p/android/issues/detail?id=4394.但是有一种强烈的感觉可以做到.

欢迎所有建议.

Dee*_*G M 54

想解决这个问题.

问题:如何使用基于对话框和全屏的相同活动.

方案:

  1. 使用主题在AndroidManifest.xml中定义您的活动 @android:style/Theme.Dialog
  2. 在您的相应.Java文件中,检查intent定义dialog模式的额外内容.
  3. 如果它不存在,请将其设置Themeandroid.R.style.Theme.theme如果您未定义任何主题,则这是应用的默认值.

代码:

boolean fDialogMode = getIntent().hasExtra("dialog_mode");

if( ! fDialogMode ) {
    super.setTheme(android.R.style.Theme);
}
Run Code Online (Sandbox Code Playgroud)

替代解决方案:

更复杂的解决方案是使用AlertDialog如下:

  1. 定义一个ListAdapter扩展的类ArrayAdapter.
  2. 返回1getCount功能

    @Override
    public int getCount() { return 1; }
    
    Run Code Online (Sandbox Code Playgroud)
  3. getView功能,inflatelayoutactivity,你需要和返回之前做任何定制view.

    @Override
    public View getView( int position, View view, ViewGroup group ) {
        View v = view;
        if( v == null ) {
            v = getSystemService(Context.LAYOUT_INFLATER_SERVICE).inflate( <layout res id>, null );
        }
    
    ... Do any customization here    ....
    
          return v;
    }
    
    Run Code Online (Sandbox Code Playgroud)

这绝对是第二选择,如果你没有做太多的处理,activity class这可能是一个选择.

只考虑这个解决方案的理由可能是在a中显示它的逻辑与dialog它用作对话的地方是隔离的.

这两个选项对我有用,但由于显而易见的原因,我选择了第一个选项.:-)


Ahm*_*lem 45

您可以使用setTheme(..)之前调用setContentView(...)super.oncreate() 它应该工作正常

  • 在super.onCreate之前将调用移到setTheme让它对我有用,谢谢! (4认同)

use*_*982 11

和其他几个一样,在onCreate中调用setTheme(在调用super.onCreate之前或之后)都不起作用.但是,通过重写setTheme,我能够指定除Manifest.xml中所述之外的主题.具体来说,以下工作没有问题:

@Override
public void setTheme(int resid) {
    boolean changeTheme = true;
    super.setTheme(changeTheme ? android.R.style.Theme_Dialog : resid);
}
Run Code Online (Sandbox Code Playgroud)

我在讨论中找到了以上内容:https://code.google.com/p/android/issues/detail?id = 4394


Reu*_*ton 10

Activity.setTheme()在打电话onCreate()之前打电话setContentView().

  • 虽然Reuben有效(我之前也尝试过),但我看到的是Black Background而不是调用Activity (2认同)