Passing data between a fragment and its container

2018-12-31 03:24发布

How can I pass data between a fragment and its container activity? Is there something similar to passing data between activities through intents?

I read this, but it didn't help much:
http://developer.android.com/guide/topics/fundamentals/fragments.html#CommunicatingWithActivity

12条回答
十年一品温如言
2楼-- · 2018-12-31 03:43

I don't know if this is the best way or not Bu I have been searching on google for quite a while finding how can I pass a Bundle from a fragment to its container activity but all I found was sending data from activity to fragment instead (which was a bit confusing for me as I'm a newbie).

later I tried something own my own that exactly worked for me as I wanted. so I'll post it here case someone like me looking for the same thing.

// Passing data from Fragment .

Bundle gameData = new Bundle();
        gameData.putStringArrayList(Constant.KEY_PLAYERS_ARR,players);
        gameData.putString(Constant.KEY_TEAM_NAME,custom_team_name);
        gameData.putInt(Constant.KEY_REQUESTED_OVER,requestedOver);

        Intent intent = getActivity().getIntent();
        intent.putExtras(gameData);

// Getting data from the bundle from it's container activity .

Bundle gameData = getIntent().getExtras();
        if (gameData != null)
        {
            int over = gameData.getInt(Constant.KEY_REQUESTED_OVER);
            ArrayList<String> players = gameData.getStringArrayList(Constant.KEY_PLAYERS_ARR);
            String team = gameData.getString(Constant.KEY_TEAM_NAME);

        }
        else if (gameData == null)
        {
            Toast.makeText(this, "Bundle is null", Toast.LENGTH_SHORT).show();
        }
查看更多
不流泪的眼
3楼-- · 2018-12-31 03:45

Another simple way to get datas, passed from another activity, in a fragment in a container activity : for example :

Activity_A => Activity_B(Fragment)

In your Activity_A you create an intent like you're sending a data (String here) to another activity :

Intent intent = new Intent(getBaseContext(),Activity_B.class);
intent.putExtra("NAME", "Value");
startActivity(intent);

in your Fragment, contained in your Activity_B :

String data = getActivity().getIntent().getExtras();
查看更多
孤独寂梦人
4楼-- · 2018-12-31 03:49

This is working for me..

in Activity add this method

    public void GetData(String data)
     {
        // do something with your data        
     }

and in Fragment add this line

((YourActivity)getContext).GetData("your data here");
查看更多
十年一品温如言
5楼-- · 2018-12-31 03:50

Interface is one of the best solutions:

Glue Interface:

public interface DataProviderFromActivity {

    public String getName();
    public String getId);

}  

MyActivity:

public class MyActivity implements DataProviderFromActivity{

    String name = "Makarov";
    String id = "sys533";

    ... ... ... ... ... .... .... 
    ... ... ... ... ... .... .... 

    public String getName(){
        return name;
    };
    public String getId(){
        return id;
    };
}

MyFragment:

public class MyFragment extends Fragment{

    String fragName = "";
    String fragId = "";

    ... ... ... ... ... .... .... 
    ... ... ... ... ... .... .... 

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        DataProviderFromActivity myActivity= (DataProviderFromActivity) getActivity();
        fragName = myActivity.getName();
        fragId = myActivity.getId();

        ... ... ... ... ... .... .... 
        ... ... ... ... ... .... .... 

        updateFragmentView();
    }
}
查看更多
琉璃瓶的回忆
6楼-- · 2018-12-31 03:50

I used an AppCompatActivity that implements Date Listeners. Fragments came as a necessity since I needed to code a date range selector. And I also needed the container to receive the selected dates to return them to the parent activity.

For the container activity, this is the class declaration:

public class AppCompatDateRange extends AppCompatActivity implements
    DateIniRangeFragment.OnDateIniSelectedListener, DateFimRangeFragment.OnDateFimSelectedListener

And the interfaces for the callbacks:

@Override
public void onDateIniSelected(String dataIni) {
    Log.i("data inicial:", dataIni);
}

@Override
public void onDateFimSelected(String dataFim) {
    Log.i("data final:", dataFim);
}

The callbacks are strings because dates are params in an query select.

The code for the fragments (based on the initial date fragment):

public class DateIniRangeFragment extends Fragment {
OnDateIniSelectedListener callbackIni;

private DatePicker startDatePicker;

public DateIniRangeFragment() {
    ///required empty constructor
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

///through this interface the fragment sends data to the container activity
public interface OnDateIniSelectedListener {
    void onDateIniSelected(String dataIni);
}

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

    ///initial date for the picker, in this case, current date
    startDatePicker = (DatePicker) v.findViewById(R.id.start_date_picker_appcompat);
    Calendar c = Calendar.getInstance();
    int ano = c.get(Calendar.YEAR);
    int mes = c.get(Calendar.MONTH);
    int dia = c.get(Calendar.DAY_OF_MONTH);
    startDatePicker.setSpinnersShown(false);
    startDatePicker.init(ano, mes, dia, dateSetListener);

    return v;
}

///listener that receives the selected date
private DatePicker.OnDateChangedListener dateSetListener = new DatePicker.OnDateChangedListener() {
    public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
        if (view.isShown()) { ///if the datepicker is on the screen
            String sDataIni = year + "-" + (monthOfYear + 1) + "-" + dayOfMonth;
            callbackIni.onDateIniSelected(sDataIni); //apply date to callback, string format
        }
    }
};

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

    /*
    * this function guarantees that the container activity implemented the callback interface
    * */
    try {
        callbackIni = (OnDateIniSelectedListener) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString() + " deve implementar OnDateIniSelectedListener");
    }
}

}

To compose the container + fragments, I used an ViewPager (AppCompat) with a custom class that extends FragmentPagerAdapter. No dialogs.

查看更多
倾城一夜雪
7楼-- · 2018-12-31 03:51

In your fragment you can call getActivity().

This will give you access to the activity that created the fragment. From there you can obviously call any sort of accessor methods that are in the activity.

e.g. for a method called getResult() on your Activity:

((MyActivity) getActivity()).getResult();
查看更多
登录 后发表回答