agentmg123 agentmg123 - 2 months ago 16
Android Question

My is my setOnClickListener giving me an error?

When I hover over the squiggly red line under "setOnClickListener", there's a pop-up message saying "Cannot resolve symbol setOnClickListener", "@Override" says "Annotations are not allowed here." and the v from "View v" is also giving me an error. Where did I mess up?

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;

public class EmailReceiptActivity extends AppCompatActivity {


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

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_options_menu, menu);
menu.findItem(R.menu.main_options_menu).setIntent(
new Intent(EmailReceiptActivity.this, LaunchActivity.class));
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//use the id of the item from main_options_menu
if (id == R.id.logoff_menu_item) {
super.onOptionsItemSelected(item);
startActivity(item.getIntent());
}

return true;
}

Button btn_send = (Button)findViewById(R.id.send_receipt_button);
btn_send.setOnClickListener(new View.OnClickListener(){
@Override
//Use the name of the function you assigned to the xml design of the button
public void onClick(View v){
//Use the name of this class, and the name class where you want to be taken when the button is clicked.
startActivity (new Intent(EmailReceiptActivity.this, SuccessActivity.class));
}
}


}

Answer

You should move the code to within a method such as onCreate in order for the onClickListener to be set. You cannot execute code like that outside a function body. Also it may be more useful to declare your Button with a more global scope, outside of onCreate, so try...

public Button btn_send;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_email_receipt);

    btn_send = (Button)findViewById(R.id.send_receipt_button);
    btn_send.setOnClickListener(new View.OnClickListener(){
        @Override
        //Use the name of the function you assigned to the xml design of the   button
        public void onClick(View v){
            //Use the name of this class, and the name class where you want to be taken when the button is clicked.
            startActivity (new Intent(EmailReceiptActivity.this, SuccessActivity.class));
    }
}