Launch Intent from onclicklistener

I am trying to start a new action from a custom onclick listener. But its impossible to access an instance of MainActivity from an onclick listener. In addition, it shows the wrong constructor for the 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.

+6
source share
5 answers

Change 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); } 
+23
source

try it

 @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 works

+4
source

pass activity context to custom onclick listener and use this context for 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); 
+4
source

Replace MainActivity.this with view.getContext() and it will work.

+2
source

I try this and it works, I want to show Toast and then move on 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; } } 

}

0
source

Source: https://habr.com/ru/post/956307/


All Articles