How Do I Start Another Activity When A Button Defined In Main.xml Is Clicked
Solution 1:
Your second activity HelloWorld
doesn't have set a content view so it doesn't find the Button
and you throw a NullPointerException
. You have to set a contentView with setContentView
containing the Button
with the id R.id.button1
like you did in the MainActivity
.
Your HelloWorld
activity:
publicclassHelloWorld<AlertDialogActivity> extendsActivity{
protectedvoidonCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.layout_hello);
finalButtonbutton= (Button) findViewById(R.id.button1);
button.setOnClickListener(newView.OnClickListener() {
publicvoidonClick(View view) {
Toast.makeText(getApplicationContext(), "You clicked on OK", Toast.LENGTH_SHORT).show();
}
});
}
}
Where R.layout.layout_hello
represents a xml file in the res/layout
folder (named layout_hello.xml
):
<?xml version="1.0" encoding="utf-8"?><LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="fill_parent"android:layout_height="fill_parent" ><Buttonandroid:id="@+id/button1"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="Button1" /></LinearLayout>
It's the same thing like you did in the MainActivity
.
Solution 2:
simple way
inlude android:onClick="onClickMyButton"
as a attribute of Button
in main.xml
remove onClickListener
from this Button
now define this mathod in your Main Activity
publicvoidonClickMyButton(View view){
Intent intent = newIntent(Main.this, HelloWorld.class);
startActivity(intent);
}
now start your application it should work fine
Solution 3:
Why did you comment that line? //setContentView(R.layout.content_layout_id);
The activity is looking for the button R.id.button1
is a null view.
Solution 4:
ya you must need to use setContentView()
un comment that code and try again
Post a Comment for "How Do I Start Another Activity When A Button Defined In Main.xml Is Clicked"