mike mike - 27 days ago 10
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);

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

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

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


Any help is greatly appreciated.

Answer

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() {
     @Override
     public void onClick(View view) {
          Log.i(TAG,"CLICKED");
          Intent intent = new Intent(YOUR_CLASS.this, Main2Activity.class);
          startActivity(intent);
      }
});