有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java我无法在onCreate方法中设置主类变量

Main类有两个要访问另一个类的变量:

public class MyClassA extends Activity {
int i = 1;
Button b1; 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        this.i = 31;
        this.b1 = (Button) findViewById(R.id.btn1);
        ~~
    }
 }

第二个类要调用mainClass对象中的变量:

public class MyclassB implements OnClickListener{
     MyClassA mainClass = new MyClassA();
     Button btn = mainClass.b1;
     int n = mainClass.i;
     public void OnClick(View arg0){
         Log.v("btn:",btn);
         Log.v("int:",n);
     }

     //btn returns null;
     //int returns 1;

但是onCreate方法没有设置变量

为什么不设置像this.i=31这样的主要类变量呢


共 (2) 个答案

  1. # 1 楼答案

    -使用内部类

    public class MyClassA extends Activity {
    int i = 1;
    Button b1; 
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            this.i = 31;
            this.b1 = (Button) findViewById(R.id.btn1);
            ~~
        }
    
    
       class MyclassB implements OnClickListener{
    
    // You can directly access the members of the Outer class from the Inner Class
    
         Button btn = b1;     
         int n = i;
    
         public void OnClick(View arg0){
             Log.v("btn:",btn);
             Log.v("int:",n);
         }
    
     }
    
    }
    
  2. # 2 楼答案

    当你像一个简单的类一样实例化你的活动时,它不会执行onCreate(),这就是为什么i值保持为1。当您使用IntentActivity时,将调用onCreate()

    如前所述,您可能需要使用内部类(或匿名类)。阅读此documentation了解更多信息