简体   繁体   English

将数据从活动传递到FragmentPagerAdapter中包含的片段

[英]Passing data from an activity to a fragment contained within a FragmentPagerAdapter

Okay so following what Google suggest ie the majority of calls should be made through the activity, I have decided to call a datepickerdialog from the activity. 好吧,按照Google的建议,即应通过活动进行大部分通话,我决定从活动中调用datepicker对话框。 This is triggered by a button click from the fragmentService class, in which I have created an interface for. 这是由fragmentService类中的一个按钮单击触发的,在其中创建了一个接口。

The datepickerdialog does load and I do get the results back from the user input. datepickerdialog确实已加载,并且确实从用户输入中获取了结果。 However the issue that I am facing is how I get the data back to the fragmentService from the Activity. 但是,我面临的问题是如何将数据从活动返回到fragmentService。 I can successfully get the ID of the fragment from the FragmentPagerAdapter, but that is it. 我可以从FragmentPagerAdapter成功获取片段的ID,仅此而已。

From what I have searched I cannot find a similar example. 根据我的搜索,我找不到类似的示例。

Please see the code below. 请参见下面的代码。

public class MyPagerAdapter extends FragmentPagerAdapter {

private List<Fragment> fragments;

public MyPagerAdapter(FragmentManager fm) {
    super(fm);
    this.fragments = new ArrayList<Fragment>();

    //  add to the arraylist all of the different fragments
    fragments.add(new fragmentAboutCar());
    fragments.add(new fragmentMPG());
    fragments.add(new fragmentServicing());

}


@Override
public Fragment getItem(int position) {
    return fragments.get(position);
}

@Override
public int getCount() {
    return fragments.size();
}

@Override
//  sets the title of each page
public CharSequence getPageTitle(int position) {

    String title = null;
    switch(position){
    case 0:
        title = "About Car";
        break;
    case 1:
        title = "MPG";
        break;
    case 2:
        title ="Servicing";
        break;
    case 3:
        title = "Pink"; 
        break;
    }
    return title;
}
}

public class MainActivity extends FragmentActivity implements fragmentServicing.callBack{

MyPagerAdapter pageAdapter;
ViewPager pager;
int id_dialog = 1;
int yr, day, month = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    //  gets the current date info
    Calendar today = Calendar.getInstance();
    yr = today.get(Calendar.YEAR);
    month = today.get(Calendar.MONTH);
    day = today.get(Calendar.DAY_OF_MONTH);


    pageAdapter = new MyPagerAdapter(getSupportFragmentManager());
    pager = (ViewPager)findViewById(R.id.myViewPager);
    pager.setAdapter(pageAdapter);
    pager.setCurrentItem(1);//  middle of the items


}
//  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(this, 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);

                //  gets a reference to the fragment
                fragmentServicing service = (fragmentServicing)
                        getSupportFragmentManager().findFragmentById(R.layout.fragment_servicing);

                if (service != null) {
                    // Call a method in the fragmentServicing to update its content
                    service.setDateService(yr, month, day);
                }
                else{

                    int result = pager.getId();
                    Log.d("null", "reading NULL");
                    //  gets the current fragment identification
                    int id = pager.getCurrentItem();
                    Fragment f = pageAdapter.getItem(id);



                    //fragmentServicing f = new fragmentServicing();
                    //f.setDateService(1991, 02, 14);
                    Log.d("id", "THE ID IS "+id);



                }

            }
        };

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.main, menu);

    return super.onCreateOptionsMenu(menu);
}

@Override
  public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case R.id.about:
        Log.d("button1", "Plus button pressed");
      break;
    case R.id.button2:
        Log.d("button2", "Minus button pressed");

      break;

    default:
      break;
    }

    return true;
  }

@Override
//  this is from the servicing fragment
public void onItemSelected(String id) {

    Log.d("from cooler", id);
    showDialog(1);

} 


}

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

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

}


@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");
    }
}

public void setDateService(int year, int month, int day)
{
    txtService.setText(Integer.toString(year));
}

@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");
        }

    });

    mot.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            showDatePicker();
            Log.d("datePressed", "Pressed the date");

        }

        private void showDatePicker() {
            DatePickerFragment date = new DatePickerFragment();

            Calendar calender = Calendar.getInstance();

            // TODO Auto-generated method stub

        }
    });
    return view;
}
}

I ran into the same issue. 我遇到了同样的问题。 I believe Google is causing some heartache because of their somewhat blanket answer of always communicating to fragments through the main activity. 我相信Google之所以会令人有些痛心,是因为他们总是通过主要活动与片段进行交流,但答案有些笼统。

This is true for most cases, but not strictly for dialog pop-ups. 在大多数情况下都是如此,但对于对话框弹出窗口并不严格。 There seems to be no good reason to go through all these extra lengths for dialogs that are meant to be transient, like number/date pickers. 似乎没有充分的理由要遍历所有这些额外的长度来进行短暂的对话框,例如数字/日期选择器。

My suggestion -- launch the dialog fragment from your fragment and all your troubles will disappear. 我的建议-从片段中启动对话框片段,所有麻烦都将消失。

For other fragment-to-fragment communication, follow the guidelines. 对于其他片段到片段的通信,请遵循准则。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM