简体   繁体   中英

How to start a new activity on click in Android?

public void onClick(View view) {
    TextView snt = (TextView)
            view.findViewById(R.id.shape_name_text);
    String Selected = snt.getText().toString();
    String triangle = getResources().getString(R.string.triangle);
    if (Selected.equals(triangle)) {


        Intent intent = new Intent(this, TriCalculator.class);
        startActivity(intent);
    }

}

My intent is showing several errors and I can't figure out what to do next.

Listing the errors would be helpful but here are at least two:

This line

TextView snt = (TextView) view.findViewById(R.id.shape_name_text);

is telling it to look in the View clicked (probably a Button ) for your TextView which it is obviously not there. Assuming shape_name_text is in the same layout as your Button just remove view`

TextView snt = (TextView) findViewById(R.id.shape_name_text);

Second problem is in this line

Intent intent = new Intent(this, TriCalculator.class);

this refers to the Listener if you are in an inner-class. Change that to

Intent intent = new Intent(v.getContext(), TriCalculator.class);

Edit

As blackbelt pointed out in a comment, the first part of the answer is assuming you have attached the OnClickListener on a View and not a ViewGroup which contains the View you are then trying to initialize.

Another Edit

It seems (through a deleted comment) that the proper Intent import wasn't added

import android.content.Intent;

Use This:

findViewById(R.id.shape_name_text);  

remove view.

public void onClick(View view) {
TextView snt = (TextView)
        view.findViewById(R.id.shape_name_text);
String Selected = snt.getText().toString();
String triangle = getResources().getString(R.string.triangle);
if (Selected.equals(triangle)) {


    Intent intent = new Intent(this, TriCalculator.class);
    startActivity(intent);
}
}

In the code you posted above, you're actually telling the OS that you want to call another OnClickListener, by passing this as a parameter for your new Intent . In order for it to work, you will need to change it to something like:

Intent intent = new Intent(MainActivity.this, TriCalculator.class);

or

Intent intent = new Intent(getAppplicationContext(), TriCalculator.class);

(There are other options also)

:) Hope this helps!

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM