【问题标题】:passing variable status between classes在类之间传递变量状态
【发布时间】:2013-07-14 12:33:08
【问题描述】:

我在一个类中创建一个布尔变量值并在另一个类中访问该变量的状态,基于布尔变量状态我的列表视图显示项目,

所以我的问题是

  1. 如何创建一个全局布尔变量
  2. 如何将它传递给另一个类
  3. 二等舱怎么查

【问题讨论】:

  • 可以创建一个静态字段,例如public static boolean variable
  • 为什么你需要它成为一个真正的全球化?假设您正在讨论在活动之间传递它,您可以轻松地在您将用于创建第二个活动的意图中传递变量值。
  • 可能重复的问题检查这个Android Global

标签: android class variables boolean


【解决方案1】:

1. A类变量

public class A{
    public String aClassVar="hello";
    }

在 B 类中使用

A obj=new A();
String inBClass=obj.aClassVar;

2.要将数据从一个Activity传递到Another Activity,您可以使用Intent,记住您的Class应该只扩展Activity比你可以使用Intent传递数据

示例

使用第一个活动发送数据:

Intent i = new Intent(this, SecondClassName.class);
i.putExtra("key", "Value");// key is used to get value in Second Activiyt
startActivity(i); 

使用以下方式接收第二个活动的数据:

Intent intent = getIntent();
String temp = intent.getStringExtra("key");// usr getStringExtra() If your extra data is represented as strings:

你必须在AndroidManifest.xml中设置Activity Name

喜欢:

<activity android:name="yourPackageName.SecondClassName" />

【讨论】:

    【解决方案2】:

    让我建议 3 个选项。

    您想在 Android 活动之间传递一个布尔变量吗?如果是这样,您可能需要使用Bundle。是的,那些在onCreate() 上给活动的小东西。您可以将自己的变量传递给这些变量,在您的情况下为布尔值,使用 putBoolean()getBoolean()

    您更喜欢使用 Android 的 SharedPref 吗?它是一个界面,用于在应用的各个部分之间共享小偏好,例如布尔标志,并将其存储起来以备后用。

    或者,您可以只实现一个单例类,该类具有布尔变量和其他变量,您需要在应用程序中存储和检查不同的类。

    【讨论】:

      【解决方案3】:

      如果您只是想访问另一个类中的对象或变量的值,请将其设为Static,然后当您需要它的值时,请这样做

      public class tempClass {
      
         public void tempMethod() {
      
           boolean status = myClass.myVariable ; // where myVariable is static boolean varaible of myClass
        }
      }
      

      但请确保在其中存储了一些值后访问该变量。

      如果您想将值发送到另一个活动,请使用意图发送值。

      例如。

      Bundle myBund = new Bundle();
      
      myBund.putBoolean(myBool);
      
      Intent intent = new Intent(myClass.this, tempClass.class);
      
      intent.putExtras("myKey",myBund);
      
      startActivity(myBund);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-11-03
        • 1970-01-01
        • 2015-04-03
        • 2014-09-06
        • 2022-10-12
        • 2012-02-21
        • 2017-10-24
        • 1970-01-01
        相关资源
        最近更新 更多