I am new to java and android. Here I am trying to set up my onclicklistener so when clicked, it will show another activity, ie ActivityB.class. The problem is with Intent i = new Intent(context, ActivityB.class);
I am not sure what to put there for context
. I tried to use this
and context
, and both are wrong.
Could you please kindly explain when and why I should use this
and when to use other terms for the context
?
public class MainActivity extends Activity {
Button b;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(context, ActivityB.class);
startActivity(i);
}
});
}
Change the code to.
b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(MainActivity.this, ActivityB.class);
startActivity(i);
}
});
As you need to pass context while using intent.
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, ActivityB.class));
}
});
Fastest method! Hope it helps! :D
1) Replace context with getApplicationContext()
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(),ActivityB.class);
startActivity(intent);
}
});
2) Replace context with MainActivity.this
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,ActivityB.class);
startActivity(intent);
}
});
Hope it will help you!
Try this..
If you declare ActivityB.class
in manifest this should work.
Intent i = new Intent(MainActivity.this, ActivityB.class);
startActivity(i);
Intent i = new Intent(this, ActivityB.class);
startActivity(i);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.