public void onClick(View v) { switch (v.getId()) { case R.id.btnGallery: Intent intent = new Intent(this, ClassName1.class); startActivity(intent); break; case R.id.btnNew: intent = new Intent(this, ClassName2.class); startActivity(intent); break; case R.id.btnPrice: intent = new Intent(this, ClassName3.class); startActivity(intent); break; case R.id.btnCallBack: intent = new Intent(this, ClassName4.class); startActivity(intent); break; ... } } 

Since there is a lot of monotonous work (call activity), I would like to optimize.

Something like that:

 public void classUsing (String s) { Intent intent = new Intent(this, s.class); startActivity(intent); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btnGallery: classUsing(ClassName1); break; case R.id.btnNew: classUsing(ClassName2); break; case R.id.btnPrice: classUsing(ClassName3); break; ... } } 

How to transfer the class name as an argument to another method and use it there?

  • one
    You could just startActivity(intent) for cases and that's all. It will be much more concise than writing a separate method. - pavlofff pm

1 answer 1

<ИмяКласса>.class is of type Class . You can pass a class as an argument to a method like this:

 public void doSomething(Class clazz) { Intent i = new Intent(context, clazz); } 

Use method:

 doSomething(Class1.class); 
  • Thanks, but how to actually transfer the name of the class? because case R.id.btnGallery: classUsing (ClassName); break; causes an error - user208111
  • one
    @ user208111 classUsing(ClassName.class); - Regent
  • Thanks for the help!!! =) - user208111