105

I am learning to build android applications and I need some specific help. I can't seem to get my head around which bits of template code I am required to change, and which bits are static.

In the LAYOUT folder I have my ACTIVITY_MAIN.XML which reads

 <?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:orientation="horizontal">

 <Button
    android:id="@+id/button1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="@string/main_buttons_photos" />

 </LinearLayout>

Next, I have my second activity ACTIVITY_SEND_PHOTOS.XML which is

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent" >

 <TextView
    android:id="@+id/textView2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:text="@string/hello_world"
    tools:context=".SendPhotos" />

 <TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:text="@string/title_activity_send_photos"
    android:textAppearance="?android:attr/textAppearanceLarge" />

 </RelativeLayout>

I then have my MainActivity.java (is this the .class?) this reads package com.example.assent.bc;

 import android.os.Bundle;
 import android.app.Activity;
 import android.view.Menu;
 import android.view.View;

 public class MainActivity extends Activity {

 @Override
 public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_main);
 }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
     getMenuInflater().inflate(R.menu.activity_main, menu);
     return true;
 }
 /** Called when the user clicks the Send button */
 public void sendMessage(View view) {
     // Do something in response to button
 }
 }

and then my SendPhotos.java file which is;

 package com.example.assent.bc;

 import android.os.Bundle;
 import android.app.Activity;
 import android.view.Menu;
 import android.view.MenuItem;
 import android.support.v4.app.NavUtils;

 public class SendPhotos extends Activity {

 @Override
 public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_send_photos);
    getActionBar().setDisplayHomeAsUpEnabled(true);
 }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_send_photos, menu);
    return true;
 }


 @Override
 public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            NavUtils.navigateUpFromSameTask(this);
            return true;
    }
    return super.onOptionsItemSelected(item);
 }

 }

I would like the button in my main activity to link through to my sendphotos activity, simply opening up that activity, nothing fancy, not sending any data or anything.

I know that somewhere I need my

 Intent i = new Intent(FromActivity.this, ToActivity.class);
 startActivity(i);

but I have no idea what to replace ToActivity.class with or what else I need where.

4

12 Answers 12

168

You can move to desired activity on button click. just add this line.

android:onClick="sendMessage"

xml:

 <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="sendMessage"
        android:text="@string/button" />

In your main activity just add this method:

public void sendMessage(View view) {
    Intent intent = new Intent(FromActivity.this, ToActivity.class);
    startActivity(intent);
}

And the most important thing: don't forget to define your activity in manifest.xml

 <activity
      android:name=".ToActivity"
      android:label="@string/app_name"/>
5
  • 3
    You must add > in the activity tag Commented Sep 21, 2013 at 18:04
  • 2
    This is not working for me. The View , Intent and the activity names are in red. Do I need to import anything for View? Commented Jul 7, 2015 at 23:15
  • 1
    @SrujanBarai yes, both import android.view.View; and import android.content.Intent; must be imported Commented Dec 22, 2016 at 4:06
  • It worked fine for me. However doesn't he need a setOnClickListener() on his button? Commented Oct 24, 2018 at 0:29
  • 1
    @VaggelisManousakis no its not required because it is already there in xml android:onClick="sendMessage"
    – Juned
    Commented Nov 8, 2019 at 15:42
30

Try this

  Button button;

public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_main);

button=(Button)findViewById(R.id.button1);
        button.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        // TODO Auto-generated method stub
                        Intent i = new Intent(getApplicationContext(),SendPhotos.class);
                        startActivity(i);
                    }
                });

 }
4
  • but where? I get errors all over the place If i try place this withing the .java in eclipse Commented Nov 2, 2012 at 12:08
  • @HenryAspden import onclocklistener and Button.
    – J.D.
    Commented Nov 2, 2012 at 12:10
  • @HenryAspden put this code after onCreate and after finding your id.
    – J.D.
    Commented Nov 2, 2012 at 12:14
  • @HenryAspden i have edit my code now try this. i have put this code in onCreate try this way.
    – J.D.
    Commented Nov 2, 2012 at 12:15
13

From Activity : where you are currently ?

To Activity : where you want to go ?

Intent i = new Intent( MainActivity.this, SendPhotos.class); startActivity(i);

Both Activity must be included in manifest file otherwise it will not found the class file and throw Force close.

Edit your Mainactivity.java

crate button's object;

now Write code for click event.

        Button btn = (button)findViewById(R.id.button1);
         btn.LoginButton.setOnClickListener(new View.OnClickListener() 
       {

                @Override
                public void onClick(View v) 
                {
                 //put your intent code here
                }
   });

Hope it will work for you.

2
  • does this go within the layout or the .java? Commented Nov 2, 2012 at 12:07
  • ok you can put this code in button's click event in main activity.java file Commented Nov 2, 2012 at 12:13
12
Button btn = (Button) findViewById(R.id.button1);

btn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Intent myIntent = new Intent(MainActivity.this, MainActivity2.class);
        MainActivity.this.startActivity(myIntent);       
    }  
});

The answer for the complete noob from a complete noob: MainActivity is the name of the first activity. MainActivity2 is the name of the second activity. button1 is the I.D of the button in xml for MainActivity Activity.

2
  • 1
    just to help others... by "name of the button" are you refering to the ID? Commented Jul 8, 2013 at 13:22
  • Indeed . Corrected to reflect your reccomendation Commented Jul 9, 2013 at 0:44
5

just follow this step (i am not writing code just Bcoz you may do copy and paste and cant learn)..

  1. first at all you need to declare a button which you have in layout

  2. Give reference to that button by finding its id (using findviewById) in oncreate

  3. setlistener for button (like setonclick listener)

  4. last handle the click event (means start new activity by using intent as you know already)

  5. Dont forget to add activity in manifest file

BTW this is just simple i would like to suggest you that just start from simple tutorials available on net will be better for you..

Best luck for Android

4

Replace the below line code:

import android.view.View.OnClickListener;
public class MainActivity extends Activity implements OnClickListener{
   Button button;
    @Override
     public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button=(Button)findViewById(R.id.button1);
        button.setOnClickListener(this);
      }
       public void onClick(View v) {
        if(v.getId==R.id.button1){
      Intent i = new Intent(FromActivity.this, ToActivity.class);
               startActivity(i);
            }
        }
     }

Add the below lines in your manifest file:

   <activity android:name="com.packagename.FromActivity"></activity>
   <activity android:name="com.packagename.ToActivity"></activity>
3

Replace your MainActivity.class with these code

public class MainActivity extends Activity {

Button b1;
@Override
public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 b1=(Button)findViewById(R.id.button1);
 b1.setOnClickListener(new View.onClickListener()
 {
  public void onClick(View v)
   {
       Intent i=new Intent(getApplicationContext(),SendPhotos.class);
       startActivity(i);
    }
 }
 )
}

Add these Code in your AndroidManifest.xml after the </activity> and Before </application>

<activity android:name=".SendPhotos"></activity>
2

This always works, either one should be just fine:

@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    Button btn = (Button) findViewById(R.id.button1);
    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick (View v) {
            startActivity(new Intent("com.tobidae.Activity1"));
        }
        //** OR you can just use the one down here instead, both work either way
        @Override
        public void onClick (View v){
            Intent i = new Intent(getApplicationContext(), ChemistryActivity.class);
            startActivity(i);
        }
    }
}
2

add below code to activity_main.xml file:

<Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="buttonClick"
        android:text="@string/button" />

and just add the below method to the MainActivity.java file:

public void buttonClick(View view){
  Intent i = new Intent(getApplicationContext()SendPhotos.class);
  startActivity(i);
}
2
  • You have a typo in, a question mark before the name of the file Commented Oct 22, 2017 at 10:44
  • Sorry for the mistake Commented Oct 23, 2017 at 7:33
1

If you have two buttons and have the same id call to your button click events like this:

Button btn1;
Button btn2;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    btn1= (Button)findViewById(R.id.button1);

    btn1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent=new Intent(MainActivity.this,target.class);
            startActivity(intent);
        }
    });

    btn2=(Button) findViewById(R.id.button1);//Have same id call previous button---> button1

    btn2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

        }
    });

When you clicked button1, button2 will work and you cannot open your second activity.

1
 <Button
            android:id="@+id/btnSignIn"
            android:layout_width="250dp"
            android:layout_height="40dp"
            android:layout_marginEnd="8dp"
            android:layout_marginLeft="8dp"
            android:layout_marginRight="8dp"
            android:layout_marginStart="8dp"
            android:layout_marginTop="16dp"
            android:background="@drawable/circal"
            android:text="Sign in"
            android:textColor="@color/white"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/etPasswordLogin" />

IN JAVA CODE

Button signIn= (Button) findViewById(R.id.btnSignIn);

signIn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(SignInPage.this,MainActivity.class));
            }
        });

}

1

You can move to desired activity on button click. just add
android:onClick="timerApp"this line.

xml:

 <Button
        android:id="@+id/timer_app"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="timerApp"
        android:text="Click To run Timer Activity" />

In your main activity just add this method:

 public void timerApp(View view){
        Intent intent= new Intent(MainActivity.this,TimerActivity.class);
        startActivity(intent);
    }

OR in onCreate() method add below code

Button btn =findViewById(R.id.timer_app);//Don't need to type casting in android studio 3

btn.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        Intent intent = new Intent(MainActivity.this, TimerActivity.class);
        startActivity(intent);       
    }  
});

Not the answer you're looking for? Browse other questions tagged or ask your own question.