I'm trying to create a simple button that opens to a different activity:
package com.example.xxx.buttonexample;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.view.View;
import android.view.View.OnClickListener;
public class MainActivity extends Activity {
Button button;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnClick();
}
public void btnClick() {
button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v)
{
Intent intent = new Intent(this,emergencyIntent.class);
startActivity(intent);
}
});
}
}
Here is my emergencyIntent.class file:
package com.example.xxx.buttonexample;
import android.app.Activity;
import android.os.Bundle;
public class emergencyIntent extends Activity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// The activity is being created.
}
}
I received a error:
"Cannot resolve constructor 'intent(anonymous android.view.View.OnClickListener, java.lang.Class(com.example.xxx.buttonexample.emergencyIntent))'.
Just replace this
in first parameter with MainActivity.this
. like:
Intent intent = new Intent(MainActivity.this,emergencyIntent.class);
The error is because you are writing it in public void onClick(View v)
, where 'this
' will mean instance of anonymous class that implements View.OnClickListener
. while first parameter in Intent constructor Intent(Context context, Class<?> cls)
requires Activity context.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With