Hello friends, in this tutorial we will teach you how to open an activity on button click.
First Create a new activity.
Note :- If you don't know how to create new activity than first real this create a new Activity.
Now Create a Button.
We use Intent for open a new activity on button click.
see the below code :-
activity_main.xml
Code Image :-
MainActivity.java
Code Image :-
activity_main2.xml
Code Image :-
Main2Activity.java
Code Image :-
Output :-
App Run
Now click on Button and see the output like this picture
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<Relativelayout android:layout_height="match_parent"
android:layout_width="match_parent"
tools:context=".MainActivity"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<Button
android:id="@+id/btn"
android:layout_centerinparent="true"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Button"/>
</Relativelayout>
Code Image :-
MainActivity.java
package com.akshayarora.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button)findViewById(R.id.btn);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,Main2Activity.class);
startActivity(intent);
}
});
}
}
Code Image :-
activity_main2.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Main2Activity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Welcome"
android:layout_centerInParent="true"/>
</RelativeLayout>
Code Image :-
Main2Activity.java
package com.akshayarora.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
public class Main2Activity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
}
}
Code Image :-
Output :-
App Run
Now click on Button and see the output like this picture
Enjoy !







No comments:
Post a Comment
Note: Only a member of this blog may post a comment.