简体   繁体   中英

Passing values from a fragment to another activity

I have a DialogFragment which has a listView as container. I've set up OnItemClickListener on the listView.

How can I get the value when the user touchs an item and pass it to another activity then store that value into a variable? I need to set a count down timer depending on which item will be selected. Actually can only display simple toast message with the item position.

As a note, the activity to which the value will be passed is not the fragment activity.

I was thinking about Bundle but have not having much knowledge on programming is a pain even after reading documentation on Google site.

on the MainActivy, here is how I set the timer:

new CountDownTimer(30000, 1000) {

        public void onTick(long millisUntilFinished) {
            String elapsedTime = String.valueOf(millisUntilFinished / 1000);
            timer.setText(elapsedTime);
        }
        public void onFinish() {
            timer.setText(R.string.text);
        }
    }.start();
}

Exemple:

If user touches item 1 then the timer gets value 15 minutes and so on...

Please guide me, thank you.

So, you want to pass data from Fragment to Activity. Here is how you do it.

Passing the data from Fragment to Activity:

final Intent intent = new Intent(getActivity(), ActivityName.class);
intent.putExtra("counter-value", counterValue);
getActivity().startActivity(intent);

Reading the value in the Activity:

final Bundle extras = getIntent().getExtras();
if(extras != null) {
    final int counterValue = extras.getInt("counter-value", -1);
    showCountDown(counterValue);
}

Now, Pass the value to the countdowntimer .

private void showCountDown(final int counterValue) {
    new CountDownTimer(counterValue, 1000) {

        public void onTick(long millisUntilFinished) {
            String elapsedTime = String.valueOf(millisUntilFinished / 1000);
            timer.setText(elapsedTime);
        }
        public void onFinish() {
            timer.setText(R.string.text);
        }
    }.start();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM