java 从片段返回值

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 从片段返回值相关的知识,希望对你有一定的参考价值。

public class DeviceActivity extends BaseActivity implements OnTimePickedListener {    
    ...
    
    /**
     * On time picked event, converts hour and minutes values to milliseconds
     * milliseconds and sets a new value for the layout in the activity.
     * @param layoutId      QuietHoursFrom or QuietHoursTo layout Id.
     * @param hour          Hour value.
     * @param minute        Minutes value.
     */
    @Override
    public void onTimePicked(int layoutId, int hour, int minute) {
        Long timeInMillis = TimeUtil.getTimeInMilliseconds(hour, minute);
        
        // Here you can do whatever needed with value obtained from the fragment
    }
    
    ...
}
/**
 * This class is used so values from TimePickerFragment could be 
 * returned back to the activity from which it was called. 
 */
public class TimePickerFragment extends DialogFragment implements TimePickerDialog.OnTimeSetListener {
    OnTimePickedListener mCallback;
    Integer mLayoutId = null;

    /**
     * An interface containing onTimePicked() method signature.
     * Container Activity must implement this interface.
     */
    public interface OnTimePickedListener {
        public void onTimePicked(int textId, int hour, int minute);
    }

    /* (non-Javadoc)
     * @see android.app.DialogFragment#onAttach(android.app.Activity)
     */
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        try {
            mCallback = (OnTimePickedListener)activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString() + " must implement OnTimePickedListener.");
        }
    }

    /* (non-Javadoc)
     * @see android.app.DialogFragment#onCreateDialog(android.os.Bundle)
     */
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        mCallback = (OnTimePickedListener)getActivity();

        Bundle bundle = this.getArguments();
        mLayoutId = bundle.getInt("layoutId");
        int hour = bundle.getInt("hour");
        int minute = bundle.getInt("minute");

        // Create a new instance of TimePickerDialog and return it
        return new TimePickerDialog(getActivity(), this, hour, minute, DateFormat.is24HourFormat(getActivity()));
    }

    /* (non-Javadoc)
     * @see android.app.TimePickerDialog.OnTimeSetListener#onTimeSet(android.widget.TimePicker, int, int)
     */
    public void onTimeSet(TimePicker view, int hour, int minute) {
        if(mCallback != null)
        {
            mCallback.onTimePicked(mLayoutId, hour, minute);
        }
    }
}

以上是关于java 从片段返回值的主要内容,如果未能解决你的问题,请参考以下文章

从使用 wkwebview 返回值的 javascript 调用 swift 函数

将字符串从对话框片段返回到活动 [重复]

java 循环变量

22.java方法的定义

启动对话框以获取结果以将值返回给主要活动

从片段返回到另一个片段的按钮