How do I get a button to open another activity?

前端 未结 8 987
执笔经年
执笔经年 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:08

    Write code on xml file.

    <Button android:width="wrap_content"
            android:height="wrap_content"
            android:id="@+id/button"
            android:text="Click"/>
    

    Write Code in your java file

    Button button=(Button)findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                startActivity(new Intent(getApplicationContext(),Secondclass.class));
               /* if you want to finish the first activity then just call
                finish(); */
            }
        });
    
    0 讨论(0)
  • 2020-12-02 14:14

    A. Make sure your other activity is declared in manifest:

    <activity
        android:name="MyOtherActivity"
        android:label="@string/app_name">
    </activity>
    

    All activities must be declared in manifest, even if they do not have an intent filter assigned to them.


    B. In your MainActivity do something like this:

    Button btn = (Button)findViewById(R.id.open_activity_button);    
    
    btn.setOnClickListener(new View.OnClickListener() {         
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MainActivity.this, MyOtherActivity.class));
            }
    });
    
    0 讨论(0)
提交回复
热议问题