【问题标题】:access integer anywhere outside method in same class在同一类中的方法之外的任何地方访问整数
【发布时间】:2015-03-31 11:11:37
【问题描述】:

我在 onConfigurationChanged 侧声明了一个 int jj 函数,现在我想在同一类的 onConfigurationChangedanywhare 之外访问它。

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);

    // Checks the orientation of the screen
    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
        Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
        final int jj=4;
    } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
        Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show(); 
        final int jj=2;   
    }
}

我想像这样在同一个类中访问这个变量:

public class MainActivity extends Activity {
    public static int aa=jj;
}

【问题讨论】:

    标签: java android integer static-variables


    【解决方案1】:

    将其声明为类字段。我不知道你在用aa 做什么。

    public class MainActivity extends Activity {
    
    public int jj;
    
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
    
        super.onConfigurationChanged(newConfig);
    
        // Checks the orientation of the screen
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
    
            jj=4;
    
        } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
            Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
    
            jj=2;
    
        }
    }
    

    }

    从问题中可以清楚地看出,您并不真正了解编程、OOP 和 Java 的基础知识。

    我建议您先完成一些基本教程,然后再继续,直到您了解原语与对象,finalstatic

    你也应该明白你不能把Activity当作POJO。

    【讨论】:

    • 我想要的是我想将 int 从 onConfigurationChanged 传递给静态变量。注意:aa 是静态整数。
    • 如果你不去听别人给你的建议和答案,那我帮不了你。我已经在你之前的问题中解释过你不应该使用static,因为你甚至不应该尝试从另一个类访问Activity。如果你对学习不感兴趣,那我也没兴趣帮忙。
    【解决方案2】:

    好吧,你可以创建一个类来保存全局变量:

    public class GlobalVariables {
         public static int jj = 0;
    }
    

    然后您可以通过简单地调用GlobalVariables.jj从任何地方访问它

    例如

        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
            GlobalVariables.jj=4;
        } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
            Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
            GlobalVariables.jj=2;
        }
    

        public static int aa= 0;
        ...
        aa = GlobalVariables.jj;
    

    但是,我非常同意西蒙的观点。您需要学习面向对象设计的基础知识,因为您提出的问题违反了一些 OOD 原则,而我建议的解决方案绝对是矫枉过正。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-01
      • 2017-01-08
      • 2016-09-17
      • 1970-01-01
      • 1970-01-01
      • 2020-03-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多