首页 \ 问答 \ 将数据从DatePickerDialog获取到片段(Getting data from a DatePickerDialog to a fragment)

将数据从DatePickerDialog获取到片段(Getting data from a DatePickerDialog to a fragment)

如上所述,我试图找出如何传回用户选择的日期。 我已经研究了如何使用onDateSet方法获取日期,但我不知道如何将其反馈给父片段,然后将EditText文本设置为选定的日期。

package com.example.androidvehicle;

import java.util.Calendar;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;

public class fragmentServicing extends Fragment  {


    callBack mCallBack;

    Button mot;
    Button servicing;
    Button tax;
    EditText txtService;

    final int Date_Dialog_ID=0;
    int cDay,cMonth,cYear; // this is the instances of the current date
    Calendar cDate;
    int sDay,sMonth,sYear; // this is the instances of the entered date

    int id_dialog = 1;
    int yr, day, month = 0;

    //  interfacing back to activity
    public interface callBack
    {
        public void onItemSelected(String id);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_servicing, container, false);
        txtService = (EditText) view.findViewById(R.id.txtServiceDate);
        mot = (Button) view.findViewById(R.id.buttonMOT);
        servicing = (Button) view.findViewById(R.id.buttonService);
        servicing.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                //  this will then pass back to the activity the string hello
                mCallBack.onItemSelected("hello");

                getActivity().showDialog(1);

            }

        });

        mot.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                getActivity().showDialog(1);



            }

        });

        return view;
    }



    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        // This makes sure that the container activity has implemented
        // the callback interface. If not, it throws an exception
        try {
            mCallBack = (callBack) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnHeadlineSelectedListener");
        }
    }



//  this is an override for when the dialog is created
    protected Dialog onCreateDialog(int id)
    {
        switch(id)
        {
        //  this will return a date picker dialog if 1 is passed
        //  could use another number for another dialog
        case 1:
            //  passes it the current date

            return new DatePickerDialog(getActivity(), mDateSetListener, yr, month, day);
        }
        return null;
    }
    //  this returns the date back that has been selected by the user

    private DatePickerDialog.OnDateSetListener mDateSetListener = 
            new DatePickerDialog.OnDateSetListener() {

                @Override
                public void onDateSet(DatePicker view, int year, int monthOfYear,
                        int dayOfMonth) {

                    yr = year;
                    month = monthOfYear;
                    day = dayOfMonth;

                    Log.d("date selected", "year "+ yr+  " month " +month+" day "+day);


                }


            };

}

As above I am trying to work out how to pass back the date selected by the user. I have worked out how to get the date selected by using the onDateSet method but I do not know how to feed this back to the parent fragment, and then set the EditText text to the date selected.

package com.example.androidvehicle;

import java.util.Calendar;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;

public class fragmentServicing extends Fragment  {


    callBack mCallBack;

    Button mot;
    Button servicing;
    Button tax;
    EditText txtService;

    final int Date_Dialog_ID=0;
    int cDay,cMonth,cYear; // this is the instances of the current date
    Calendar cDate;
    int sDay,sMonth,sYear; // this is the instances of the entered date

    int id_dialog = 1;
    int yr, day, month = 0;

    //  interfacing back to activity
    public interface callBack
    {
        public void onItemSelected(String id);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_servicing, container, false);
        txtService = (EditText) view.findViewById(R.id.txtServiceDate);
        mot = (Button) view.findViewById(R.id.buttonMOT);
        servicing = (Button) view.findViewById(R.id.buttonService);
        servicing.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                //  this will then pass back to the activity the string hello
                mCallBack.onItemSelected("hello");

                getActivity().showDialog(1);

            }

        });

        mot.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                getActivity().showDialog(1);



            }

        });

        return view;
    }



    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        // This makes sure that the container activity has implemented
        // the callback interface. If not, it throws an exception
        try {
            mCallBack = (callBack) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnHeadlineSelectedListener");
        }
    }



//  this is an override for when the dialog is created
    protected Dialog onCreateDialog(int id)
    {
        switch(id)
        {
        //  this will return a date picker dialog if 1 is passed
        //  could use another number for another dialog
        case 1:
            //  passes it the current date

            return new DatePickerDialog(getActivity(), mDateSetListener, yr, month, day);
        }
        return null;
    }
    //  this returns the date back that has been selected by the user

    private DatePickerDialog.OnDateSetListener mDateSetListener = 
            new DatePickerDialog.OnDateSetListener() {

                @Override
                public void onDateSet(DatePicker view, int year, int monthOfYear,
                        int dayOfMonth) {

                    yr = year;
                    month = monthOfYear;
                    day = dayOfMonth;

                    Log.d("date selected", "year "+ yr+  " month " +month+" day "+day);


                }


            };

}

原文:https://stackoverflow.com/questions/21443109
更新时间:2023-10-30 22:10

最满意答案

您可以将该console.log移动到嵌套after

describe('all my tests', () => {

  it('#1', done => setTimeout(done, 500))
  it('#2', done => setTimeout(done, 500))
  it('#3', done => setTimeout(done, 500))

  after(() => {

    context('Context of test suite', () => {

      it('test case name', () => {})

      after(() => {
        console.log('foo');
      });
    })

  });

});

虽然我很难理解你为什么要使用这样的设置。 一个问题是您不能在根级别after使用此设置(在任何describe块之外),并且, after不用于其他测试之后,它意味着测试之后进行清理。

我可能会使用这样的东西:

describe('all my tests', () => {

  it('#1', done => setTimeout(done, 500))
  it('#2', done => setTimeout(done, 500))
  it('#3', done => setTimeout(done, 500))

});

describe('Context of test suite', () => {

  it('test case name', () => {})

  after(() => {
    console.log('foo');
  });
})

即只是放置必须运行的套件,最后,最后。 如果您愿意,可以在套件外部移动最后一个并将其提升到根级钩子。


You can move that console.log into a nested after:

describe('all my tests', () => {

  it('#1', done => setTimeout(done, 500))
  it('#2', done => setTimeout(done, 500))
  it('#3', done => setTimeout(done, 500))

  after(() => {

    context('Context of test suite', () => {

      it('test case name', () => {})

      after(() => {
        console.log('foo');
      });
    })

  });

});

Although I have a hard time understanding why you'd use a setup like this. One issue is that you can't use this setup inside a root-level after (one that's outside of any describe block), and also, after isn't meant for additional tests, it's meant to clean up after tests.

I would probably use something like this:

describe('all my tests', () => {

  it('#1', done => setTimeout(done, 500))
  it('#2', done => setTimeout(done, 500))
  it('#3', done => setTimeout(done, 500))

});

describe('Context of test suite', () => {

  it('test case name', () => {})

  after(() => {
    console.log('foo');
  });
})

I.e. just place the suite that has to run last, well, last. You can move that last after outside of the suite and promote it to a root-level hook, if you like.

相关问答

更多
  • 我看到的唯一问题是你的beforeEach钩子没有返回它的诺言。 删除大括号以使箭头的右侧表达式应该起作用: beforeEach(() => startServer(4000).then(() => { console.log('Server started') client = SocketCluster.connect(options) }) ); 或这个: beforeEach(() => { return startServer(4000).then(() => { ...
  • 在执行HTTP请求时,使用三个参数调用回调函数: 错误(可能的错误返回) res(HTTPRequest对象) 身体(身体的缓冲) 因此,regErr在body变量中。 而且由于你正在渲染一个HTML页面,你将不得不自己解析它以找到它。 一种可能的解决方案是渲染JSON并在结果体缓冲区上使用JSON.parse()。 When doing an HTTP request, the callback function is called with three arguments: err (Possible ...
  • 如果声明一个done参数,Mocha将传入一个回调函数并等待它被调用,然后再运行下一个测试。 it('works', function (done) { // ... done(); }); 我猜这就是你想要的。 这实际上是使测试“异步”,因为下一个测试用例不会在上一次返回后立即调用。 默认为“同步”。 您也done在before , after , beforeEach和afterEach before使用done 。 如果将参数传递给done函数,则会使测试用例失败。 If you declare a ...
  • 你可以做的是在你的测试中注入$location和$route服务。 设置whenGET来拦截实际请求,然后在转换完成后检查$location和$route配置。 我之前做过类似的事 it("should load the page.", inject(function ($rootScope, $location, $route, $httpBackend) { $httpBackend.whenGET("scripts/my-module/views/my-module.html").re ...
  • 得到它的工作,从{pattern: 'test/mock/description.xml', watched: false, served: true}中省略了“included:false”,这导致它默认为true。 这导致业力试图将其包含在导致错误的html中。 Got it to work, had left out "included: false" from {pattern: 'test/mock/description.xml', watched: false, served: true} w ...
  • 你的想法在这里似乎几乎完全错误。 首先,你正在编写和使用setExp ,就好像它是一个同步操作,但事实并非如此。 它将在请求发送到redis之前返回。 它也不会返回任何东西,所以即使它是同步的,也会result你的测试总是undefined. 您需要重新设计setExp作为异步操作,可以通过使用async关键字,返回承诺或让它接受回调函数。 其次,如果您希望在Redis密钥上设置过期时间,则应在设置密钥本身时进行设置,而不是在没有过期的情况下设置密钥,然后尝试稍后添加过期时间。 否则,你会冒失败的风险,然后 ...
  • 您可以将该console.log移动到嵌套after : describe('all my tests', () => { it('#1', done => setTimeout(done, 500)) it('#2', done => setTimeout(done, 500)) it('#3', done => setTimeout(done, 500)) after(() => { context('Context of test suite', () => { ...
  • NSStream是一个抽象类,既不会将数据读取也不会将数据写入流中。 要实际访问数据,您需要一个具体的子类,例如NSInputStream或NSOutputStream (或NSOutputStream的自定义子类)。 要读取NSInputStream的数据,请调用read:maxLength: . 您可能希望使用hasBytesAvailable轮询流,询问是否有任何新数据可用。 NSOutputStream具有类似的write:maxLength:和hasSpaceAvailable方法。 iOS文档强 ...
  • 必须为async方法调用异步方法异步的单元测试? 不,但这样做是最自然的。 如果它使用Task.Run()同步调用异步方法,会丢失什么? 真的没什么。 它的性能稍差,但在某种程度上你可能永远不会注意到。 您可能希望使用GetAwaiter().GetResult()而不是Result来避免失败测试中的AggregateException包装。 你也可以直接调用这个方法; 无需将其包装在Task.Run 。 他们说这种缺乏支持是有正当理由的,我并不反对。 哦,我当然不同意他们。 :) 这是否意味着他们无法单元 ...
  • 看来mocha正在并行运行所有测试文件,这是否正确? 没有。 默认情况下,Mocha按顺序加载测试文件,并记录必须运行的所有测试,然后按顺序逐个运行测试。 无论测试是在同一个文件还是在不同的文件中,Mocha都不会同时运行两个测试。 请注意,无论您的测试是异步还是同步,都没有区别:当Mocha启动异步测试时,它会等待它完成,然后再进行下一次测试。 有一些工具可以修补Mocha并行运行测试。 因此,您可能会看到显示Mocha测试并行运行的演示, 但这需要额外的工具,并且不是Mocha正确说话的一部分 。 如果 ...

相关文章

更多

最新问答

更多
  • 获取MVC 4使用的DisplayMode后缀(Get the DisplayMode Suffix being used by MVC 4)
  • 如何通过引用返回对象?(How is returning an object by reference possible?)
  • 矩阵如何存储在内存中?(How are matrices stored in memory?)
  • 每个请求的Java新会话?(Java New Session For Each Request?)
  • css:浮动div中重叠的标题h1(css: overlapping headlines h1 in floated divs)
  • 无论图像如何,Caffe预测同一类(Caffe predicts same class regardless of image)
  • xcode语法颜色编码解释?(xcode syntax color coding explained?)
  • 在Access 2010 Runtime中使用Office 2000校对工具(Use Office 2000 proofing tools in Access 2010 Runtime)
  • 从单独的Web主机将图像传输到服务器上(Getting images onto server from separate web host)
  • 从旧版本复制文件并保留它们(旧/新版本)(Copy a file from old revision and keep both of them (old / new revision))
  • 西安哪有PLC可控制编程的培训
  • 在Entity Framework中选择基类(Select base class in Entity Framework)
  • 在Android中出现错误“数据集和渲染器应该不为null,并且应该具有相同数量的系列”(Error “Dataset and renderer should be not null and should have the same number of series” in Android)
  • 电脑二级VF有什么用
  • Datamapper Ruby如何添加Hook方法(Datamapper Ruby How to add Hook Method)
  • 金华英语角.
  • 手机软件如何制作
  • 用于Android webview中图像保存的上下文菜单(Context Menu for Image Saving in an Android webview)
  • 注意:未定义的偏移量:PHP(Notice: Undefined offset: PHP)
  • 如何读R中的大数据集[复制](How to read large dataset in R [duplicate])
  • Unity 5 Heighmap与地形宽度/地形长度的分辨率关系?(Unity 5 Heighmap Resolution relationship to terrain width / terrain length?)
  • 如何通知PipedOutputStream线程写入最后一个字节的PipedInputStream线程?(How to notify PipedInputStream thread that PipedOutputStream thread has written last byte?)
  • python的访问器方法有哪些
  • DeviceNetworkInformation:哪个是哪个?(DeviceNetworkInformation: Which is which?)
  • 在Ruby中对组合进行排序(Sorting a combination in Ruby)
  • 网站开发的流程?
  • 使用Zend Framework 2中的JOIN sql检索数据(Retrieve data using JOIN sql in Zend Framework 2)
  • 条带格式类型格式模式编号无法正常工作(Stripes format type format pattern number not working properly)
  • 透明度错误IE11(Transparency bug IE11)
  • linux的基本操作命令。。。