mike mike - 1 year ago 71
Android Question

Android app button not working

I have used this snippet of code in a few other projects, but I cannot understand why it will not work here. It is a simple button that changes activities. The code is giving the error message: cannot resolve the symbol "setOnClickListener"

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;

public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {

public static String value2;
public static String value3;
public static String value4;
public static String value5;
public static String value6;
public static String value7;
public static String value8;
public Spinner spinnerMath;
public Spinner spinnerEnglish;
public Spinner spinnerHistory;
public Spinner spinnerScience;
public Spinner spinnerLanguage;
public Spinner spinnerReligion;
public Spinner spinnerSeventh;
public Button button = (Button) findViewById(R.id.button);

protected void onCreate(Bundle savedInstanceState) {

button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {

Intent intent = new Intent(getBaseContext(), Main2Activity.class);

Any help is greatly appreciated.

Answer Source

Make sure your view id is the same with the one you want to click. replace this to YOUR_CLASS.this. If intent give you an error says something about manifest, then check you manifest if Main2Activity.class is declare as activity

Button button = (Button)findViewById(R.id.button_name);    
button.setOnClickListener(new View.OnClickListener() {
     public void onClick(View view) {
          Intent intent = new Intent(YOUR_CLASS.this, Main2Activity.class);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download