【问题标题】:android accessing variables through classesandroid通过类访问变量
【发布时间】:2012-03-22 18:03:52
【问题描述】:

我有这个应用程序有 2 个类,在第一个类中我定义了一个列表数组,我想在我的第二个类中访问它,我该怎么做?第一类(数组扩展listActivity,另一个类扩展Activity)。我不认为发布我的代码是必要的,因为我相信有一个快速的解决方案,我只是不知道。尽管如果您在没有看到实际代码的情况下无法帮助我,我可以发布它。

【问题讨论】:

  • 在我看来,这些示例都需要我创建一个实现 parcelable 的类?但我需要将我的整个数组从 listactivity 类发送到一个活动类,在这里找不到任何有效的东西.. :(

标签: android class variables


【解决方案1】:

您可以使用自定义 ApplicationContext 在活动之间共享全局状态 - 请参阅 here 了解更多详细信息...

【讨论】:

    【解决方案2】:

    您可以使用intentExtras 跨活动传递ArrayList<String>

     ArrayList<String> myArrayList = new ArrayList<String>();
     // populate your array  -> if you want to send objects make a string form of them
    
     Intent myIntent = new Intent(this, Activit2.class);
     mtIntent.putStringArrayList("my_array_list", myArrayList);
    

    在 Activity2 中

    Intent intent = getIntent();
     List<String> stringMediaList = intent.getStringArrayListExtra("my_array_list");
    
    for (int i = 0; i < stringMediaList.size(); i++) {
       //reconstruct object if needed
    }
    

    如果您不想使用 parcelable,这将起作用

    【讨论】:

    • 非常感谢!效果很好,不过如果你看到这个,这只是最后一个问题。如何将 int 传递给另一个类? (没有 intArray 只是一个普通的 int)应该有类似的方式吧?
    • 是的,myIntent.putIntegerArrayListExtra("my_integer_array", value) 其中 value 是一个 ArrayList。对于常规 int 使用 myIntent.putExtra("my_int" , 9001);
    猜你喜欢
    • 2011-07-14
    • 1970-01-01
    • 2020-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-26
    相关资源
    最近更新 更多