简体   繁体   English

将值从片段传递到另一个活动

[英]Passing values from a fragment to another activity

I have a DialogFragment which has a listView as container.我有一个 DialogFragment,它有一个 listView 作为容器。 I've set up OnItemClickListener on the listView.我已经在 listView 上设置了 OnItemClickListener。

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.我正在考虑 Bundle,但即使在阅读了 Google 网站上的文档后,对编程的了解也不多。

on the MainActivy, here is how I set the timer:在 MainActivy 上,这是我设置计时器的方法:

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...如果用户触摸项目 1,则计时器将获得 15 分钟的值,依此类推...

Please guide me, thank you.请指导我,谢谢。

So, you want to pass data from Fragment to Activity.因此,您希望将数据从 Fragment 传递到 Activity。 Here is how you do it.这是你如何做到的。

Passing the data from Fragment to Activity:将数据从 Fragment 传递到 Activity:

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

Reading the value in the Activity:读取 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 .现在,将值传递给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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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