-3

I just started learning the programming language like java and android I and creating status and quotes application where I have 10 WhatsApp buttons and 10 textviews. I want when WhatsApp button 1 is clicked then textview 1 will be shared on WhatsApp and same for the rest buttons but for this I have to create 10 methods for these 10 buttons but this is very bad coding standard, I also tried if else condition in this method but it also not worked, so please suggest me a better idea so that I can implement that in my method.

Thank you

ॐ Rakesh Kumar
  • 1,318
  • 1
  • 14
  • 24

1 Answers1

0

you can create method like this

public void shareInWhatsapp(String text){
    Intent whatsappIntent = new Intent(Intent.ACTION_SEND);
    whatsappIntent.setType("text/plain");
    whatsappIntent.setPackage("com.whatsapp");
    whatsappIntent.putExtra(Intent.EXTRA_TEXT, text);
    try {
        activity.startActivity(whatsappIntent);
    } catch (android.content.ActivityNotFoundException ex) {
        //whatsapp not installed
    }

}

And use it like this

btnWhatsapp1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            shareInWhatsapp(textView1.getText().toString());
        }
    });
Radesh
  • 13,084
  • 4
  • 51
  • 64
  • Thanks man it worked but for every button we have to put onclick on every button is there any other way like switch or if else – Rohan Saini Oct 13 '18 at 14:17
  • i don't think so, you must call shareInWhatsapp() 10 time but you can use Custom ListView for this – Radesh Oct 13 '18 at 14:23
  • If I was in your place use listView . but is totally diffrent – Radesh Oct 13 '18 at 14:24
  • Thanks man i tried switch instead of setting on click on every button it worked properly for me, thanks thanks thanks – Rohan Saini Oct 13 '18 at 14:27
  • instead of switch you can use impliment onClick. check this answer https://stackoverflow.com/a/30142323/6401241 – Radesh Oct 13 '18 at 14:31