问题描述:

I'm trying to make a simple button that switches between two activites but I'm having several problems.

My code for the entire mainactivity is as follows:

 package com.example.project.arithmeticalarm;

import android.content.Intent;

import android.support.v7.app.ActionBarActivity;

import android.os.Bundle;

import android.view.Menu;

import android.view.MenuItem;

import android.widget.Button;

import android.view.View;

import android.view.View.OnClickListener;

public class MainActivity extends ActionBarActivity {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

}

@Override

public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu; this adds items to the action bar if it is present.

getMenuInflater().inflate(R.menu.menu_main, menu);

return true;

}

@Override

public boolean onOptionsItemSelected(MenuItem item) {

// Handle action bar item clicks here. The action bar will

// automatically handle clicks on the Home/Up button, so long

// as you specify a parent activity in AndroidManifest.xml.

int id = item.getItemId();

//noinspection SimplifiableIfStatement

if (id == R.id.action_settings) {

return true;

}

return super.onOptionsItemSelected(item);

}

Button newAlarm= (Button)findViewById(R.id.newAlarm);

newAlarm.setOnClickListener(new OnClickListener);{

public void onClick(View v){

startActivity(new Intent(MainActivity.this, CreateAlarm.class));

}

});

}

Everything except the button text at the end was created by default so I havent touched that, but afaik this should be working. The problems I'm having specifically are that I'm getting a "cannot resolve symbol OnClickListener" error, and also a "cannot resolve symbol v", as well as various squiggly red lines around the v and on the final closing bracket.

Please help this is driving me crazy.

网友答案:

Write

Button newAlarm= (Button)findViewById(R.id.newAlarm);
newAlarm.setOnClickListener(new View.OnClickListener){
    @Override
    public void onClick(View v){
        startActivity(new Intent(MainActivity.this, CreateAlarm.class));
    }
});

inside method such as in onCreate instead of class,because you must initialise view in methods.

网友答案:

Modify your OnClickListener implementation as following;

Button newAlarm= (Button)findViewById(R.id.newAlarm);
newAlarm.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v){
        startActivity(new Intent(MainActivity.this, CreateAlarm.class));
    }
});

Also do this in onCreate.

and it should be working like a charm.

相关阅读:
Top