I've seen some solutions that people have posted, but I can't find the flaw in my code. It crashes on opening.
Here's my Main activity.
public class MainActivity extends Activity
{
Button guy, girl;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
guy = (Button) findViewById(R.id.bGuy);
girl = (Button) findViewById(R.id.bGirl);
guy.setOnClickListener(new View.OnClickListener() {
public void onClick(View aView)
{
Intent toAnotherActivity = new Intent(aView.getContext(), ScreenGuy.class);
startActivityForResult(toAnotherActivity, 0);
}
});
}
}
And the .xml for it
<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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="@+id/get_over"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:text="@string/get_over"
android:textSize="20sp" />
<Button
android:id="@+id/bGuy"
android:layout_width="120dp"
android:layout_height="40dp"
android:layout_alignLeft="@+id/get_over"
android:layout_below="@+id/get_over"
android:layout_marginTop="66dp"
android:text="@string/guy"
android:onClick="sendMessage"
/>
<Button
android:id="@+id/bGirl"
android:layout_width="120dp"
android:layout_height="40dp"
android:layout_alignBaseline="@+id/bGuy"
android:layout_alignBottom="@+id/bGuy"
android:layout_alignRight="@+id/get_over"
android:text="@string/girl"
/>
I have another screen I want to move to on the button press of "Guy".
Intent intent = new Intent(MainActivity.this, ScreenGuy.class);
startActivity(intent);
EDIT: its like this because if you just say this, it refers to the context of the onclick listener class, not the activity
Use this:
Intent i = new Intent(FirstActivity.this, SecondActivity.class);
startActivity(i);
You do not pass the context of the clicked view, but the context of the application.
Change this:
Intent toAnotherActivity = new Intent(aView.getContext(), ScreenGuy.class);
startActivityForResult(toAnotherActivity, 0);
to this:
Intent toAnotherActivity = new Intent(MainActivity.this, ScreenGuy.class);
startActivity(toAnotherActivity);
For what you've said, you don't need to start the activity for result . Also, you were passing the Intent
the wrong context: aView.getContext()
. Pass it your class context.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.