在同一活动中把数据片段传递给片段[英] Pass data fragment to fragment in the same activity

本文是小编为大家收集整理的关于在同一活动中把数据片段传递给片段的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

我有一些问题,想询问有关活动中片段到片段的数据.我不知道该怎么做.有人可以帮忙吗? 这是我的代码.

sharefragment.java

package com.example.user8.myapplication;


import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;


/**    
 * A simple {@link Fragment} subclass.
 */
public class ShareFragment extends Fragment implements             AdapterView.OnItemSelectedListener{

private Spinner spinner1,spinner2,spinner3;
private Button btn_submit,btn_selDate;
private FirebaseAuth auth;
FirebaseUser firebaseUser;

public ShareFragment() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View v = inflater.inflate(R.layout.fragment_share, container, false);

    btn_selDate = (Button) v.findViewById(R.id.btn_selDate);

    btn_selDate.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // Initialize a new date picker dialog fragment
            DialogFragment dFragment = new DatePickerFragment();

            // Show the date picker dialog fragment
            dFragment.show(getFragmentManager(), "Date Picker");

        }
    });

    btn_submit = (Button) v.findViewById(R.id.btn_submit_food);

    spinner1 = (Spinner)v.findViewById(R.id.spinner_selectFood);
    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getContext(),R.array.spinner_food,R.layout.support_simple_spinner_dropdown_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner1.setAdapter(adapter);
    spinner1.setOnItemSelectedListener(this);

    spinner3 = (Spinner)v.findViewById(R.id.spinner_selectTime);
    ArrayAdapter<CharSequence> adapter3 = ArrayAdapter.createFromResource(getContext(),R.array.spinner_time,R.layout.support_simple_spinner_dropdown_item);
    adapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner3.setAdapter(adapter3);
    spinner3.setOnItemSelectedListener(this);

    auth = FirebaseAuth.getInstance();

    btn_submit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Food").push();
            firebaseUser = auth.getCurrentUser();
            String uid = firebaseUser.getUid();
            String u_food = spinner1.getSelectedItem().toString();
            String u_time= spinner3.getSelectedItem().toString();

            Food myFood = new Food(uid,u_food,"formatteddate",u_time);//data pass to here to save into firebase
            ref.setValue(myFood).addOnCompleteListener(new OnCompleteListener<Void>() {
                @Override
                public void onComplete(@NonNull Task<Void> task) {
                    if (task.isSuccessful()) {
                        Toast.makeText(getContext(), getString(R.string.share_food_success_msg), Toast.LENGTH_SHORT).show();
                        getActivity().finish();
                        startActivity(new Intent(getContext(), Main2Activity.class));
                    } else {
                        Toast.makeText(getContext(),  getString(R.string.share_food_fail_msg), Toast.LENGTH_SHORT).show();
                        getActivity().finish();
                        startActivity(new Intent(getContext(), Main3Activity.class));
                    }
                }
            });
        }
    });
    return v;
}

public static class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        final Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);

        DatePickerDialog dpd = new DatePickerDialog(getActivity(),
                AlertDialog.THEME_HOLO_LIGHT, this, year, month, day);

        /*
            add(int field, int value)
                Adds the given amount to a Calendar field.
         */
        // Add 3 days to Calendar
        calendar.add(Calendar.DATE, 3);

        dpd.getDatePicker().setMaxDate(calendar.getTimeInMillis());

        // Subtract 6 days from Calendar updated date
        calendar.add(Calendar.DATE, -6);

        // Set the Calendar new date as minimum date of date picker
        dpd.getDatePicker().setMinDate(calendar.getTimeInMillis());

        // So, now date picker selectable date range is 7 days only

        // Return the DatePickerDialog
        return dpd;
    }

    public void onDateSet(DatePicker view, int year, int month, int day) {
        // Do something with the chosen date
        TextView tv = (TextView) getActivity().findViewById(R.id.tv);

        // Create a Date variable/object with user chosen date
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(0);
        cal.set(year, month, day, 0, 0, 0);
        Date chosenDate = cal.getTime();

        // Format the date using style and locale
        DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.US);
        String formattedDate = df.format(chosenDate);

        // Display the chosen date to app interface
        tv.setText(formattedDate);//formattedDate is the data that I want to pass to myFood.
    }
}

@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
    String text = parent.getItemAtPosition(position).toString();
}

@Override
public void onNothingSelected(AdapterView<?> parent) {

}
}

我的应用程序是用户可以选择食物,选择日期(从当前日期开始7天)和时间列表,然后单击提交后.数据库将接收所有数据并保存到Firebase中.

推荐答案

我们可以使用Bundle将数据从一个fragment发送到另一个fragment

发送fragment

RecievingFragment fragment = new RecievingFragment ();
Bundle args = new Bundle();
args.putString("Key", "Value");
fragment.setArguments(args);

getFragmentManager().beginTransaction().add(R.id.container, fragment).commit();

接收fragment

在新片段的onCreateView中:

String value = getArguments().getString("YourKey");

其他推荐答案

您可以通过通过活动来做到这一点,但是调用将在第二片片段上调用methode的methode,或者,您可以通过扩展应用程序类,可以轻松地使用全局变量,这将很容易,SE如何使用全局变量与扩展应用程序类

本文地址:https://www.itbaoku.cn/post/2091069.html

问题描述

I have some problem want to ask about passing data from fragment to fragment in an activity. I have no idea how to do this. Anybody can help? Here is my code.

ShareFragment.java

package com.example.user8.myapplication;


import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;


/**    
 * A simple {@link Fragment} subclass.
 */
public class ShareFragment extends Fragment implements             AdapterView.OnItemSelectedListener{

private Spinner spinner1,spinner2,spinner3;
private Button btn_submit,btn_selDate;
private FirebaseAuth auth;
FirebaseUser firebaseUser;

public ShareFragment() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View v = inflater.inflate(R.layout.fragment_share, container, false);

    btn_selDate = (Button) v.findViewById(R.id.btn_selDate);

    btn_selDate.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // Initialize a new date picker dialog fragment
            DialogFragment dFragment = new DatePickerFragment();

            // Show the date picker dialog fragment
            dFragment.show(getFragmentManager(), "Date Picker");

        }
    });

    btn_submit = (Button) v.findViewById(R.id.btn_submit_food);

    spinner1 = (Spinner)v.findViewById(R.id.spinner_selectFood);
    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getContext(),R.array.spinner_food,R.layout.support_simple_spinner_dropdown_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner1.setAdapter(adapter);
    spinner1.setOnItemSelectedListener(this);

    spinner3 = (Spinner)v.findViewById(R.id.spinner_selectTime);
    ArrayAdapter<CharSequence> adapter3 = ArrayAdapter.createFromResource(getContext(),R.array.spinner_time,R.layout.support_simple_spinner_dropdown_item);
    adapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner3.setAdapter(adapter3);
    spinner3.setOnItemSelectedListener(this);

    auth = FirebaseAuth.getInstance();

    btn_submit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Food").push();
            firebaseUser = auth.getCurrentUser();
            String uid = firebaseUser.getUid();
            String u_food = spinner1.getSelectedItem().toString();
            String u_time= spinner3.getSelectedItem().toString();

            Food myFood = new Food(uid,u_food,"formatteddate",u_time);//data pass to here to save into firebase
            ref.setValue(myFood).addOnCompleteListener(new OnCompleteListener<Void>() {
                @Override
                public void onComplete(@NonNull Task<Void> task) {
                    if (task.isSuccessful()) {
                        Toast.makeText(getContext(), getString(R.string.share_food_success_msg), Toast.LENGTH_SHORT).show();
                        getActivity().finish();
                        startActivity(new Intent(getContext(), Main2Activity.class));
                    } else {
                        Toast.makeText(getContext(),  getString(R.string.share_food_fail_msg), Toast.LENGTH_SHORT).show();
                        getActivity().finish();
                        startActivity(new Intent(getContext(), Main3Activity.class));
                    }
                }
            });
        }
    });
    return v;
}

public static class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        final Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);

        DatePickerDialog dpd = new DatePickerDialog(getActivity(),
                AlertDialog.THEME_HOLO_LIGHT, this, year, month, day);

        /*
            add(int field, int value)
                Adds the given amount to a Calendar field.
         */
        // Add 3 days to Calendar
        calendar.add(Calendar.DATE, 3);

        dpd.getDatePicker().setMaxDate(calendar.getTimeInMillis());

        // Subtract 6 days from Calendar updated date
        calendar.add(Calendar.DATE, -6);

        // Set the Calendar new date as minimum date of date picker
        dpd.getDatePicker().setMinDate(calendar.getTimeInMillis());

        // So, now date picker selectable date range is 7 days only

        // Return the DatePickerDialog
        return dpd;
    }

    public void onDateSet(DatePicker view, int year, int month, int day) {
        // Do something with the chosen date
        TextView tv = (TextView) getActivity().findViewById(R.id.tv);

        // Create a Date variable/object with user chosen date
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(0);
        cal.set(year, month, day, 0, 0, 0);
        Date chosenDate = cal.getTime();

        // Format the date using style and locale
        DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.US);
        String formattedDate = df.format(chosenDate);

        // Display the chosen date to app interface
        tv.setText(formattedDate);//formattedDate is the data that I want to pass to myFood.
    }
}

@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
    String text = parent.getItemAtPosition(position).toString();
}

@Override
public void onNothingSelected(AdapterView<?> parent) {

}
}

My app's flow is user can choose food, select date (7 days from current date), and a list of time, then after click submit. database will receive all the data and save into firebase.

推荐答案

We can use the Bundle to send the data from one fragment to the another fragment

SendingFragment

RecievingFragment fragment = new RecievingFragment ();
Bundle args = new Bundle();
args.putString("Key", "Value");
fragment.setArguments(args);

getFragmentManager().beginTransaction().add(R.id.container, fragment).commit();

RecievingFragment

In onCreateView of the new Fragment:

String value = getArguments().getString("YourKey");

其他推荐答案

you can do it by passing through the activity, but calling a methode that will call a methode on the second fragment or , you can easly use global variable by extending tha Application class, it will be easy, se how to use global variable with extending Application class