android-fragments 如何在Android中的同一活动中将日期从一个片段传递到另一个片段?

xdnvmnnf  于 2022-11-13  发布在  Android
关注(0)|答案(3)|浏览(160)

我无法将数据(用户从日期小部件中选择的日期)从小部件传递回调用片段并将其设置在按钮上。开始片段成功地将当前日期传递到小部件,但无法将用户选择的日期传递回调用片段。
以下是起始片段(即CrimeFragment)的代码

package com.khalsa.gurankassingh.criminalintent;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;

import java.util.Date;
import java.util.UUID;

/**
 * Created by Gurankas Singh on 3/12/2017.
 */

public class CrimeFragment extends Fragment
{
    public static final String ARG_CRIME_ID = "crime_id";
    public static final String DIALOG_DATE = "DialogDate";

private static final int REQUEST_DATE = 0;

private Crime mCrime;               //instance of the Crime class
private EditText mTitleField;       // The editable text field in the fragment
private Button mDateButton;         //Displays the date of the crime on the button
private CheckBox mSolvedCheckBox;   //Displays the current status of the crime; solved or unsolved

public static CrimeFragment newInstance(UUID crimeID)           //to pass value to the fragment via an argument to another fragment
{
    Bundle args = new Bundle();
    args.putSerializable(ARG_CRIME_ID,crimeID);

    CrimeFragment fragment = new CrimeFragment();
    fragment.setArguments(args);
    return fragment;
}

@Override
public void onCreate(@Nullable Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    UUID crimeId = (UUID)getArguments().getSerializable(ARG_CRIME_ID);
    mCrime = CrimeLab.get(getActivity()).getCrime(crimeId);

}

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState)
{
    View v = inflater.inflate(R.layout.fragment_crime,container,false);

    mTitleField = (EditText) v.findViewById(R.id.crime_title);
    mTitleField.setText(mCrime.getTitle());
    mTitleField.addTextChangedListener(new TextWatcher()
    {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after)
        {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count)
        {
            mCrime.setTitle(s.toString());
        }

        @Override
        public void afterTextChanged(Editable s)
        {

        }
    });

    mDateButton = (Button) v.findViewById(R.id.crime_date);
    updateDate();
    mDateButton.setOnClickListener(new View.OnClickListener()
    {

        @Override
        public void onClick(View v)
        {
            FragmentManager fragmentManager = getFragmentManager();
            DatePickerFragment dialog = DatePickerFragment.newInstance(mCrime.getDate());
            setTargetFragment(CrimeFragment.this,REQUEST_DATE);
            dialog.show(fragmentManager, DIALOG_DATE);
        }
    });

    mSolvedCheckBox = (CheckBox) v.findViewById(R.id.crime_solved);
    mSolvedCheckBox.setChecked(mCrime.isSolved());
    mSolvedCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener()
    {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
        {
            //set the crime's solved property
            mCrime.setSolved(isChecked);
        }
    });

    return v;
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
    if (resultCode != Activity.RESULT_OK)
    {
        return;
    }
    if (requestCode == REQUEST_DATE)
    {
        Date date = (Date)data.getSerializableExtra(DatePickerFragment.EXTRA_DATE);
        mCrime.setDate(date);
        updateDate();
    }
}

private void updateDate()
{
    mDateButton.setText(DateFormat.format("EEEE, d MMMM, yyy", mCrime.getDate()));
}
}

下面是DatePickerFragment托管的datePicker小部件的代码

package com.khalsa.gurankassingh.criminalintent;

import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.DatePicker;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

/**
 * Created by Gurankas Singh on 4/9/2017.
 */

public class DatePickerFragment extends DialogFragment
{
    private static final String DATE_ARG = "date";
public static final String EXTRA_DATE = "com.khalsa.gurankassingh.criminalintent.date";

private DatePicker mDatePicker;

public static DatePickerFragment newInstance(Date date)
{
    Bundle args = new Bundle();
    args.putSerializable(DATE_ARG,date);

    DatePickerFragment fragment = new DatePickerFragment();
    fragment.setArguments(args);
    return fragment;
}

@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{
    Date date = (Date)getArguments().getSerializable(DATE_ARG);

    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);
    int year = calendar.get(Calendar.YEAR);
    int month = calendar.get(Calendar.MONTH);
    int day = calendar.get(Calendar.DAY_OF_MONTH);

    View v = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_date,null);

    mDatePicker = (DatePicker)v.findViewById(R.id.dialog_date_date_picker);
    mDatePicker.init(year,month,day,null);

    return new AlertDialog.Builder(getActivity()).setView(v).setTitle(R.string.date_picker_title).setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener()
    {
        @Override
        public void onClick(DialogInterface dialog, int which)
        {
            int year = mDatePicker.getYear();
            int month = mDatePicker.getMonth();
            int day = mDatePicker.getDayOfMonth();
            Date date = new GregorianCalendar(year, month, day).getTime();
            sendResult(Activity.RESULT_OK, date);
        }
    }).create();
}
private void sendResult(int resultCode, Date date)
{
    if (getTargetFragment() == null)
    {
        return;
    }
    Intent intent = new Intent();
    intent.putExtra(EXTRA_DATE,date);

    getTargetFragment().onActivityResult(getTargetRequestCode(), resultCode, intent);
}

}

a0zr77ik

a0zr77ik1#

要在Fragments之间传递数据,您需要知道的是:
1-要将数据从Activity传递到Fragment,请使用对象示例,因为您在Activity中创建了Fragment,因此您有一个来自Activity的示例,因此请使用该示例传递数据,如下所示:

class Activity1 extend AppCompatActivity {

   Fragment1 fragment;

   void doSomethingInFramgent() {

      fragment.doSomething();
   }
}

2-要将数据从Fragment传递到Activity,请使用Interface,创建一个Interface并使用以下步骤:
2-1-创建一个Interface文件:

public interface FragmentInteraction {
     void doSomethingInActivity();
}

2-2-在Activity中实现Interface

class Activity1 extend AppCompatActivity implement FragmentInteraction {

    void doSomethingInActivity() {
       // do whatever you need
    }
 }

2-3-从Interface创建一个对象,并在onAttach中初始化它,如下所示:

class Fragment1 extend Fragment {

   FragmentInteraction fragmentInteraction;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);

        if (context instanceof FragmentInteraction) {
            fragmentInteraction = (FragmentInteraction) context;
        }
    }

}

2-4-使用Interface示例调用Activity中方法,如下所示:

fragmentInteraction.doSomethinInActivity();

通过这个概念,您可以在FragmentsActivity之间传递数据,例如,如果您希望将数据从一个片段传递到不同Activity中的另一个片段,您可以:
活动1,片段1。活动2,片段2
Interface将数据从Fragment1传递到Activity1,用startActivityForResult启动Activity2,用fragment2对象传递数据,用Interface将数据返回到Activity2,然后使用setResult并返回到Activity1
PS:如果你想在创建Fragment对象时传递数据,你可以使用Argument来传递数据。
为此,您可以使用以下命令:
1-创建用于获取片段示例静态方法:

public static Fragment1 getInstance(String data1) {

        Fragment1 fragment = new Fragment1();

        Bundle bundle = new Bundle();
        bundle.putString(KEY, data1);
        fragment.setArguments(bundle);

        return fragment;
    }

然后在onViewCreate上的onCreateView中获取如下所示的数据:

if (getArguments() != null) {
     data = getArguments().getString(KEY);    
 }
xqk2d5yq

xqk2d5yq2#

您可以尝试以下解决方案:-
=〉更改CrimeFragment中的以下代码

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
    if (resultCode != Activity.RESULT_OK)
    {
        return;
    }
    if (requestCode == REQUEST_DATE)
    {
        long dateValue = data.getLongExtra(DatePickerFragment.EXTRA_DATE,System.currentTimeMillis());
        Date date = new Date(dateValue);
        mCrime.setDate(date);
        updateDate();
    }
}

并在DatePickerFragment中更改以下代码:-

private void sendResult(int resultCode, Date date)
        {
            if (getTargetFragment() == null)
            {
                return;
            }
            Intent intent = new Intent();
            intent.putExtra(EXTRA_DATE, date.getTime());

            getTargetFragment().onActivityResult(getTargetRequestCode(), resultCode, intent);
        }

....

gwo2fgha

gwo2fgha3#

你好试试这个方法,
您可以使用共享首选项来存储日期,以后您可以在需要时访问它,它更容易处理。只需记住日期格式并相应地选择SimpleDateFormat,因为如果输入日期的格式不相同,它会产生解析错误。

写入共享首选项

SharedPreferences sharedpreferences;
sharedpreferences = getSharedPreferences("myPref", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
            editor.putString("Date",String.valueOf(date);
            editor.commit();

需要时读取共享首选项

SharedPreferences prefs = this.getSharedPreferences("myPref", Context.MODE_PRIVATE);
String dateCrime = prefs.getString("Date", null);  

//Chose Date format depending on your date
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");  
try {  
    Date date = format.parse(dateCrime);   
} catch (ParseException e) {    
    e.printStackTrace();  
}

相关问题