【问题标题】:Android use of an string array on another methodAndroid 在另一种方法上使用字符串数组
【发布时间】:2011-02-18 04:12:09
【问题描述】:

我试图在您按下按钮后创建一个具有多项选择对话框的活动。在那里,您可以从列表中进行选择。但是这些东西是在对话框出现之前从 web 方法接收到的。

所以我在 onCreate 中接收到它们后创建了一个字符串数组,以便在那里以正确的大小对其进行初始化。 但是我的对话框方法然后无法获取数组,因为它可能超出了它的范围。 我的代码是这样的

@Override
 protected Dialog onCreateDialog(int id)
//Here is where the array is loaded to the multiple select dialog
etc


@Override
public void onCreate(Bundle savedInstanceState)
//Here is where i initialise the array and get its contents
etc

我无法在课程开始时初始化我的数组,因为我还不知道它的大小。 这与我的变量范围有关,我很困惑

【问题讨论】:

    标签: android arrays scope


    【解决方案1】:

    如果你使用 showDialog 并且想要活动管理的对话框(你应该这样做),那么你必须实现 onCreateDialog 来实际创建对话框。这将为您拥有的每个对话框调用一次。每次调用 showDialog() 时都会调用 onPrepareDialog。因此,更新显示字符串数组的对话框的代码应该放在 onPrepareDialog 中,创建对话框的代码应该放在 onCreateDialog 中。

    public Dialog onCreateDialog(int id) {
        switch(id) {
            case MY_DIALOG:
                Dialog d = new Dialog(this);
                return d;
        }
    }
    
    public void onPrepareDialog(Dialog d, int id) {
        switch(id) {
            case MY_DIALOG:
                d.setSomeStringArray();
                break;
        }
    
    }
    

    【讨论】:

      【解决方案2】:

      使字符串数组成为类成员,只需在 onCreate 中填充它。如果数组从不改变,你可以在 onCreateDialog 中将它加载到对话框中,如果它可能在对对话框的调用之间发生变化,那么你应该在 onPrepareDialog 中进行。

      所以在你的类中定义:

      private String mDialogStrings[];
      

      然后在 onCreate 中类似:

      mDialogStrings = new String[numItems];
      mDialogStrings[0] = string1;
      etc...
      

      【讨论】:

        猜你喜欢
        • 2010-09-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-06-16
        • 1970-01-01
        • 2012-10-06
        • 2022-01-11
        相关资源
        最近更新 更多