草庐IT

java - 当自定义警报对话框有一个打开的微调器时,处理方向变化的正确方法是什么?

coder 2023-12-03 原文

在我的应用程序中,我有一个自定义 AlertDialog(由系统使用 showDialog() 处理),其中包含一个带有 2 个选项卡的 tabhost。在其中一个选项卡中有一个微调器。只要未打开微调器(显示微调器对话框),我就可以毫无问题地旋转屏幕。如果微调器在旋转过程中打开,我会得到:

FATAL EXCEPTION: main
java.lang.IllegalArgumentException: View not attached to window manager
    at android.view.WindowManagerImpl.findViewLocked(WindowManagerImpl.java:355)
    at android.view.WindowManagerImpl.removeView(WindowManagerImpl.java:200)
    at android.view.Window$LocalWindowManager.removeView(Window.java:432)
    at android.app.Dialog.dismissDialog(Dialog.java:278)
    at android.app.Dialog.access$000(Dialog.java:71)
    at android.app.Dialog$1.run(Dialog.java:111)
    at android.app.Dialog.dismiss(Dialog.java:268)
    at android.widget.Spinner.onDetachedFromWindow(Spinner.java:89)
    at android.view.View.dispatchDetachedFromWindow(View.java:6173)
    at android.view.ViewGroup.dispatchDetachedFromWindow(ViewGroup.java:1164)
    at android.view.ViewGroup.dispatchDetachedFromWindow(ViewGroup.java:1162)
    at android.view.ViewGroup.dispatchDetachedFromWindow(ViewGroup.java:1162)
    at android.view.ViewGroup.dispatchDetachedFromWindow(ViewGroup.java:1162)
    at android.view.ViewGroup.dispatchDetachedFromWindow(ViewGroup.java:1162)
    at android.view.ViewGroup.dispatchDetachedFromWindow(ViewGroup.java:1162)
    at android.view.ViewGroup.dispatchDetachedFromWindow(ViewGroup.java:1162)
    at android.view.ViewGroup.dispatchDetachedFromWindow(ViewGroup.java:1162)
    at android.view.ViewGroup.dispatchDetachedFromWindow(ViewGroup.java:1162)
    at android.view.ViewGroup.dispatchDetachedFromWindow(ViewGroup.java:1162)
    at android.view.ViewGroup.dispatchDetachedFromWindow(ViewGroup.java:1162)
    at android.view.ViewGroup.dispatchDetachedFromWindow(ViewGroup.java:1162)
    at android.view.ViewRoot.dispatchDetachedFromWindow(ViewRoot.java:1746)
    at android.view.ViewRoot.doDie(ViewRoot.java:2757)
    at android.view.ViewRoot.handleMessage(ViewRoot.java:1995)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:130)
    at android.app.ActivityThread.main(ActivityThread.java:3683)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:507)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
    at dalvik.system.NativeStart.main(Native Method)

所以...

1 - 是否可以在 onPause() 期间以编程方式关闭微调器?

2 - 我应该使用其他方法吗?

3 - 如果没有合适的解决方案,我该如何捕获这个特定的异常? (我知道不好的做法,但崩溃需要停止,并且由于 Activity 在被销毁后会正确地 self 重建,所以无论如何都没有关系。

...为了所有神圣的爱,请不要建议我将 android:configChanges="orientation" 添加到我的 Activity 声明中。令我惊讶的是,它经常被接受为解决方向问题的官方解决方案。

编辑更多信息

这是我的对话框创建代码供引用:

static final int ID_DIALOG_CHOOSER = 1;
int pref_location;
private Dialog dialog;

...

protected Dialog onCreateDialog(int id)
{
    switch(id)
    {
    case ID_DIALOG_CHOOSER:
        dialog = show(ID_DIALOG_CHOOSER);
        break;
    }
    return dialog;
}

...

showDialog(DialogView.ID_DIALOG_CHOOSER);

...

Dialog show(final int dialogType) 
{
    if (dialogType == ID_DIALOG_CHOOSER)
    {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);

        // inflate tabhost layout
        View tabHostLayout = (View) inflater.inflate(R.layout.tabhost_layout, null);
        FrameLayout tabContent = (FrameLayout) tabHostLayout.findViewById(android.R.id.tabcontent);

        // inflate tab content layouts and add to tabhost layout
        LinearLayout tab1 = (LinearLayout) inflater.inflate(R.layout.dialog_tab1, null);
        tabContent.addView(tab1);
        LinearLayout tab2 = (LinearLayout) inflater.inflate(R.layout.dialog_tab2, null);
        tabContent.addView(tab2);

        // tab setup
        TabHost tabHost = (TabHost) tabHostLayout.findViewById(R.id.TabHost_Dialog_Tabs);
        tabHost.setup();

        TabHost.TabSpec tab_1 = tabHost.newTabSpec("Category 1");
        tab_1.setContent(R.id.LinearLayout_Dialog_Tab1_Content);
        tab_1.setIndicator(this.getResources().getString(R.string.dialog_tab1), this.getResources().getDrawable(R.drawable.tabhost_icon_selector));
        tabHost.addTab(tab_1);

        TabHost.TabSpec tab_2 = tabHost.newTabSpec("Category 2");
        tab_2.setContent(R.id.LinearLayout_Dialog_Tab2_Content);
        tab_2.setIndicator(this.getResources().getString(R.string.dialog_tab2), this.getResources().getDrawable(R.drawable.tabhost_icon_selector));
        tabHost.addTab(tab_2);

        // spinner setup
        final Spinner spinner_location = (Spinner) tab1.findViewById(R.id.Spinner_Dialog_Location);
        String[] locationArrayVals = null;
        ArrayAdapter<CharSequence> adapter_location = null;
        locationArrayVals = this.getResources().getStringArray(R.array.location_array_vals);
        adapter_location = ArrayAdapter.createFromResource(this, R.array.location_array_listdisplay, android.R.layout.simple_spinner_item);
        adapter_location.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner_location.setAdapter(adapter_location);

        // ok button
        Button button_ok = (Button) tab1.findViewById(R.id.Button_Dialog_OK);
        button_ok.setOnClickListener(new View.OnClickListener() 
        {
            public void onClick(View view) 
            {
                pref_location = spinner_location.getSelectedItemPosition();
                dialog.dismiss();
            }
        });

        // create dialog
        builder.setTitle("Location")
        .setView(tabHost)
        .setCancelable(true);
        dialog = builder.create();
    }
    return dialog;
}

使用临时解决方法进行编辑

对于任何感兴趣的人,我至少设法通过继承微调器并覆盖 onDetachedFromWindow() 来阻止崩溃,如下所示:

public static class CatchingSpinner extends Spinner
{
    public CatchingSpinner(Context context, AttributeSet attrs) 
    {
        super(context, attrs);
    }

    @Override
    protected void onDetachedFromWindow()
    {
        try
        {
            super.onDetachedFromWindow();
        }
        catch (IllegalArgumentException e)
        {
            // do whatever
        }
    } 
}

就像我说的,一个解决方法。仍在研究解决方案。 :/

最佳答案

我找到了更好的解决方案。用外观和行为都像 Spinner 的按钮替换 Spinner 实际上并不难(幸运的是,崩溃除外)。

<Button 
     android:background="@android:drawable/btn_dropdown" 
     android:gravity="left|center_vertical"
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" />

public void showSpinner() {
    AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
    builder.setTitle(_spinnerPrompt);
    builder.setSingleChoiceItems(_spinnerOptions, _spinnerSelection,
      new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int item) {
            _spinnerSelection = item;
            _pseudoSpinner.setText(_spinnerOptions[item]);
            _restoreSpinnerOnRestart = false;
            dialog.dismiss();
        }
    });
    builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
        @Override
        public void onCancel(DialogInterface dialog) {
            _restoreSpinnerOnRestart = false;
        }
    });
    AlertDialog alert = builder.create();
    _restoreSpinnerOnRestart = true;
    alert.show();
    }

@Override
public Bundle onSaveInstanceState() {
    Bundle state = super.onSaveInstanceState();
    state.putBoolean(STATE_SPINNER_RESTORE, _restoreSpinnerOnRestart);
    state.putInt(STATE_SPINNER_SELECTION, _spinnerSelection);
    return state;
};

@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    _spinnerSelection = savedInstanceState.getInt(STATE_SPINNER_SELECTION, -1);
    _restoreSpinnerOnRestart = savedInstanceState.getBoolean(STATE_SPINNER_RESTORE);
    _pseudoSpinner.setText(_spinnerOptions[_spinnerSelection]);

    if (_restoreSpinnerOnRestart) {
        showSpinner();
    }
};

关于java - 当自定义警报对话框有一个打开的微调器时,处理方向变化的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6906513/

有关java - 当自定义警报对话框有一个打开的微调器时,处理方向变化的正确方法是什么?的更多相关文章

  1. ruby - 如何使用 Nokogiri 的 xpath 和 at_xpath 方法 - 2

    我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div

  2. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  3. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

    类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

  4. ruby - Facter::Util::Uptime:Module 的未定义方法 get_uptime (NoMethodError) - 2

    我正在尝试设置一个puppet节点,但ruby​​gems似乎不正常。如果我通过它自己的二进制文件(/usr/lib/ruby/gems/1.8/gems/facter-1.5.8/bin/facter)在cli上运行facter,它工作正常,但如果我通过由ruby​​gems(/usr/bin/facter)安装的二进制文件,它抛出:/usr/lib/ruby/1.8/facter/uptime.rb:11:undefinedmethod`get_uptime'forFacter::Util::Uptime:Module(NoMethodError)from/usr/lib/ruby

  5. Ruby 方法() 方法 - 2

    我想了解Ruby方法methods()是如何工作的。我尝试使用“ruby方法”在Google上搜索,但这不是我需要的。我也看过ruby​​-doc.org,但我没有找到这种方法。你能详细解释一下它是如何工作的或者给我一个链接吗?更新我用methods()方法做了实验,得到了这样的结果:'labrat'代码classFirstdeffirst_instance_mymethodenddefself.first_class_mymethodendendclassSecond使用类#returnsavailablemethodslistforclassandancestorsputsSeco

  6. ruby-on-rails - Rails 3.2.1 中 ActionMailer 中的未定义方法 'default_content_type=' - 2

    我在我的项目中添加了一个系统来重置用户密码并通过电子邮件将密码发送给他,以防他忘记密码。昨天它运行良好(当我实现它时)。当我今天尝试启动服务器时,出现以下错误。=>BootingWEBrick=>Rails3.2.1applicationstartingindevelopmentonhttp://0.0.0.0:3000=>Callwith-dtodetach=>Ctrl-CtoshutdownserverExiting/Users/vinayshenoy/.rvm/gems/ruby-1.9.3-p0/gems/actionmailer-3.2.1/lib/action_mailer

  7. ruby - Highline 询问方法不会使用同一行 - 2

    设置:狂欢ruby1.9.2高线(1.6.13)描述:我已经相当习惯在其他一些项目中使用highline,但已经有几个月没有使用它了。现在,在Ruby1.9.2上全新安装时,它似乎不允许在同一行回答提示。所以以前我会看到类似的东西:require"highline/import"ask"Whatisyourfavoritecolor?"并得到:Whatisyourfavoritecolor?|现在我看到类似的东西:Whatisyourfavoritecolor?|竖线(|)符号是我的终端光标。知道为什么会发生这种变化吗? 最佳答案

  8. ruby-on-rails - 如何使用 instance_variable_set 正确设置实例变量? - 2

    我正在查看instance_variable_set的文档并看到给出的示例代码是这样做的:obj.instance_variable_set(:@instnc_var,"valuefortheinstancevariable")然后允许您在类的任何实例方法中以@instnc_var的形式访问该变量。我想知道为什么在@instnc_var之前需要一个冒号:。冒号有什么作用? 最佳答案 我的第一直觉是告诉你不要使用instance_variable_set除非你真的知道你用它做什么。它本质上是一种元编程工具或绕过实例变量可见性的黑客攻击

  9. ruby-on-rails - form_for 中不在模型中的自定义字段 - 2

    我想向我的Controller传递一个参数,它是一个简单的复选框,但我不知道如何在模型的form_for中引入它,这是我的观点:{:id=>'go_finance'}do|f|%>Transferirde:para:Entrada:"input",:placeholder=>"Quantofoiganho?"%>Saída:"output",:placeholder=>"Quantofoigasto?"%>Nota:我想做一个额外的复选框,但我该怎么做,模型中没有一个对象,而是一个要检查的对象,以便在Controller中创建一个ifelse,如果没有检查,请帮助我,非常感谢,谢谢

  10. ruby - 主要 :Object when running build from sublime 的未定义方法 `require_relative' - 2

    我已经从我的命令行中获得了一切,所以我可以运行rubymyfile并且它可以正常工作。但是当我尝试从sublime中运行它时,我得到了undefinedmethod`require_relative'formain:Object有人知道我的sublime设置中缺少什么吗?我正在使用OSX并安装了rvm。 最佳答案 或者,您可以只使用“require”,它应该可以正常工作。我认为“require_relative”仅适用于ruby​​1.9+ 关于ruby-主要:Objectwhenrun

随机推荐