有 Java 编程相关的问题?

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

java如何将变量从onClick传递到另一个类

我试图将一个名为choice的变量传递给另一个类,但我不知道该怎么做,因为它在onClick中。下面是我正在尝试做的一个例子

public int choice;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //intent for first button
    Button button1= (Button) findViewById(R.id.button1);
    button1.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            choice = 1;
            startActivity(new Intent(MainActivity.this,Celeb1.class));
        }
    });
    //intent for second button
    Button button2= (Button) findViewById(R.id.button2);
    button2.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            choice = 2;
            startActivity(new Intent(MainActivity.this,Celeb1.class));
        }
    });

}

在另一个类中,我想检查choice是否等于1或0,并执行一些代码


共 (3) 个答案

  1. # 1 楼答案

    //in main activity    
    Intent i=new Intent(getApplicationContext(),Celeb1.class);
        i.putExtra("name","stack");//name is key stack is value
        startActivity(i);
    
    
        //In Celeb1 class
    
        Intent i=getIntent();
        String name=i.getStringExtra("name");
    
  2. # 2 楼答案

    可以通过这种方式传递变量

    Intent intent = new Intent(MainActivity.this,Celeb1.class)
    intent.putExtra("choice", 1);
    startActivity(intent);
    

    在Celeb1类中,可以使用

    Bundle extras = getIntent().getExtras();
    int choice= extras.getInt("choice");
    

    内部onCreate()

  3. # 3 楼答案

    不要创建意图的实例,而是创建意图的对象,并向类传递额外的值

    选择=2

    Intent intent = new Intent(MainActivity.this, Celeb1.class);
    intent.putExtra("choice",choice);
    startActivity(intent);
    

    就这样 我是android初学者,希望能对你有所帮助