I am trying to start a new activity from a custom onclick listener. But its unable to access MainActivity instance from onclick listener. Also, its showing wrong constructor for intent. Here is my code:
public class ChartClickListener implements OnClickListener {
private String ChartLink;
public ChartClickListener(String chartLink){
this.ChartLink=chartLink;
}
@Override
public void onClick(View view) {
// TODO Auto-generated method stub
Intent intent=new Intent(MainActivity.this,ChartImageActivity.class);
intent.putExtra("chartLink", ChartLink);
startActivity(intent);
}
}
Thanks for the help in advance.
Modify your code as:
@Override
public void onClick(View view) {
// TODO Auto-generated method stub
Intent intent=new Intent(view.getContext(),ChartImageActivity.class);
intent.putExtra("chartLink", ChartLink);
startActivity(intent);
}
try like this
@Override
public void onClick(View view) {
// TODO Auto-generated method stub
Intent intent=new Intent(view.getContext(),ChartImageActivity.class);
intent.putExtra("chartLink", ChartLink);
view.getContext().startActivity(intent);//Changed Here
}
Hope It will work
pass activity context to custom onclick listener and use that context to startactivity
public class ChartClickListener implements OnClickListener {
private String ChartLink;
Context c;
public ChartClickListener(String chartLink,Context context){
this.ChartLink=chartLink;
this.c=context;
}
@Override
public void onClick(View view) {
// TODO Auto-generated method stub
Intent intent=new Intent(c,ChartImageActivity.class);
intent.putExtra("chartLink", ChartLink);
c.startActivity(intent);
}
}
set setOnClickListener as
ChartClickListener chartclicklistener=new ChartClickListener("chartLink",MainActivity.this);
b.setOnClickListener(chartclicklistener);
Replace MainActivity.this
with view.getContext()
and it will work.
I try this and it work, i want to show a Toast, and then transfer to a new Activity.
public class NumbersClickListener implements View.OnClickListener {
@Override
public void onClick(View view){
Toast.makeText(view.getContext(),"Open the list of Numbers",Toast.LENGTH_SHORT).show();
switch (view.getId()){
case R.id.numbers:
Intent i = new Intent(view.getContext(), NumberActivity.class);
view.getContext().startActivity(i);
break;
case R.id.family:
Intent i2 = new Intent(view.getContext(),FamilyActivity.class);
view.getContext().startActivity(i2);
break;
case R.id.colors:
Intent i3 = new Intent(view.getContext(),ColorsActivity.class);
view.getContext().startActivity(i3);
break;
case R.id.phrases:
Intent i4 = new Intent(view.getContext(),PhrasesActivity.class);
view.getContext().startActivity(i4);
break;
}
}
}