D
D
Daniel2018-05-16 15:57:39
Java
Daniel, 2018-05-16 15:57:39

How to pass the value of a variable to another method?

Good day!
I can't figure out how to pass the pos value from the onClick method to nextQuoteBtn to copy the quote from the array. Help implement.

//Кнопка смены цитаты
        Button nextQuoteBtn = (Button) findViewById(R.id.next_quote_btn_quote_activity);
        nextQuoteBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final int pos = random.nextInt(quotes.length);
                QuoteShowView.setText(quotes[pos]);
            }
        });

        //Кнопка "копировать"
        ImageButton copyQuoteBtn = (ImageButton) findViewById(R.id.quote_btn_copy);
        copyQuoteBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast toast = Toast.makeText(getApplicationContext(),
                        "Цитата скопирована", Toast.LENGTH_SHORT);
                toast.show();

                android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                clipboard.setText(quotes[pos]);
            }
        });

        //Кнопка "поделится"
        ImageButton shareQuoteBtn = (ImageButton) findViewById(R.id.quote_btn_share);
        shareQuoteBtn.setOnClickListener(new View.OnClickListener() {
            @Overrided 
            public void onClick(View v) {
                Intent sendIntent = new Intent();
                sendIntent.setAction(Intent.ACTION_SEND);
                sendIntent.putExtra(Intent.EXTRA_TEXT, quotes[pos]);
                sendIntent.setType("text/plain");
                startActivity(Intent.createChooser(sendIntent,"Поделиться"));
            }
        });

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Denis Zagaevsky, 2018-05-16
@zagayevskiy

Daniel , okay, I understand, but what you say PPC is incomprehensible. You want to use the same variable in different anonymous classes. I don't know why you want this, but you can do it like this
final int pos = random.nextInt(quotes.length); you replace with assignment in the field of enclosing class. Use it elsewhere.

I
Ivan Ivanov, 2018-05-16
@ZZiliST

I'm not strong in Java, but if I'm not mistaken, there are two options. Or create a global variable that will be assigned the value pos. Then you can use it in any method. Or you should change the onClick method by replacing void (returns nothing) with the desired data type, for example String and return the value pos.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question