[英]Android OnClickListener, intent and context
I am new to java and android. 我是Java和android的新手。 Here I am trying to set up my onclicklistener so when clicked, it will show another activity, ie ActivityB.class.
在这里,我试图设置我的onclicklistener,因此当单击它时,它将显示另一个活动,即ActivityB.class。 The problem is with
Intent i = new Intent(context, ActivityB.class);
问题在于
Intent i = new Intent(context, ActivityB.class);
I am not sure what to put there for context
. 我不确定要放在什么
context
。 I tried to use this
and context
, and both are wrong. 我尝试使用
this
和context
,两者都是错误的。
Could you please kindly explain when and why I should use this
and when to use other terms for the context
? 您能否请您解释何时,为何使用
this
术语以及何时针对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. 因为您需要在使用Intent时传递上下文。
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, ActivityB.class));
}
});
Fastest method! 最快的方法! Hope it helps!
希望能帮助到你! :D
:D
1) Replace context with getApplicationContext() 1)用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 2)用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. 如果您在清单中声明
ActivityB.class
,则应该可以使用。
Intent i = new Intent(MainActivity.this, ActivityB.class);
startActivity(i);
Intent i = new Intent(this, ActivityB.class);
startActivity(i);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.