How do I get a button to open another activity?

前端 未结 8 1019
执笔经年
执笔经年 2020-12-02 13:09

I\'ve added a button to my activity XML file and I can\'t get it to open my other activity. Can some please tell me step by step on how to do this?

8条回答
  •  一生所求
    2020-12-02 14:07

    Using an OnClickListener

    Inside your Activity instance's onCreate() method you need to first find your Button by it's id using findViewById() and then set an OnClickListener for your button and implement the onClick() method so that it starts your new Activity.

    Button yourButton = (Button) findViewById(R.id.your_buttons_id);
    
    yourButton.setOnClickListener(new OnClickListener(){
        public void onClick(View v){                        
            startActivity(new Intent(YourCurrentActivity.this, YourNewActivity.class));
        }
    });
    

    This is probably most developers preferred method. However, there is a common alternative.

    Using onClick in XML

    Alternatively you can use the android:onClick="yourMethodName" to declare the method name in your Activity which is called when you click your Button, and then declare your method like so;

    public void yourMethodName(View v){
        startActivity(new Intent(YourCurrentActivity.this, YourNewActivity.class));
    }
    

    Also, don't forget to declare your new Activity in your manifest.xml. I hope this helps.

    References;

    • Starting Another Activity (Official API Guide)

提交回复
热议问题