将参数从片段传递到其容器活动

时间:2016-11-24 12:23:40

标签: android android-fragments

我有两个fragments timedate picker。 我需要从片段中发送用户选择的数据并将其传递给fragments activity,以便合并数据并将其发送到另一个activity。 我使用此解决方案Link但数据为null

这是FragmentOne - FramentTwo是相同的

public FragmentOne(){}

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

   //FROM SIDE
   timeButtonFrom = (Button)view.findViewById(R.id.time_button);
   dateButtonFrom = (Button)view.findViewById(R.id.date_button);
   tvDateFrom = (TextView)view.findViewById(R.id.time_textview);
   tvTimeFrom = (TextView)view.findViewById(R.id.date_textview);


    timeButtonFrom.setOnClickListener(new View.OnClickListener() {
       @Override
       public void onClick(View view) {
           Calendar now = Calendar.getInstance();
           // TimePickerDialog tpd = TimePickerDialog.newInstance(
           TimePickerDialog tpd = TimePickerDialog.newInstance(
                   FragmentOne.this,
                   now.get(Calendar.HOUR_OF_DAY),
                   now.get(Calendar.MINUTE),true);//24H Enable, If 12 set false
           tpd.setThemeDark(true);
           tpd.enableMinutes(true);
           tpd.setTitle("Choose Time");
           tpd.setTimeInterval(1,15);//setTimeInterval to 1H and 15Min


           tpd.setOnCancelListener(new DialogInterface.OnCancelListener() {
               @Override
               public void onCancel(DialogInterface dialogInterface) {
                   Log.d("TimePicker", "Dialog was cancelled");
               }
           });

           tpd.show(getFragmentManager(), "ChooseTimeFrom");
       }
   });// end Button Listener FROM

   dateButtonFrom.setOnClickListener(new View.OnClickListener() {
       @Override
       public void onClick(View view) {
           Calendar now = Calendar.getInstance();
           DatePickerDialog dpd = DatePickerDialog.newInstance(
                   FragmentOne.this,
                   now.get(Calendar.YEAR),
                   now.get(Calendar.MONTH),
                   now.get(Calendar.DAY_OF_MONTH)
           );
           dpd.setThemeDark(true);
           dpd.showYearPickerFirst(true);
           dpd.setTitle("Choose Date");
           dpd.show(getFragmentManager(), "ChooseDateFrom");
       }
   });//END DATEBUTTONFROM
  return  view;

}//END ONCREATEVIEW

@Override
public void onResume() {
    super.onResume();
    DatePickerDialog dpd = (DatePickerDialog) getFragmentManager().findFragmentByTag("ChooseDateFrom");
    if(dpd != null) dpd.setOnDateSetListener(this);
    TimePickerDialog tpd = (TimePickerDialog) getFragmentManager().findFragmentByTag("ChooseTimeFrom");
    if(tpd != null) tpd.setOnTimeSetListener(this);

}



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

    String date = "You picked the following date: "+year+"/"+(++monthOfYear)+"/"+dayOfMonth;
    tvDateFrom.setText(date);

}

@Override
public void onTimeSet(RadialPickerLayout view, int hourOfDay, int minute, int second) {

    String hourString = hourOfDay < 10 ? "0"+hourOfDay : ""+hourOfDay;
    String minuteString = minute < 10 ? "0"+minute : ""+minute;
    String secondString = second < 10 ? "0"+second : ""+second;
    String time = "You picked the following time: "+hourString+"h"+minuteString+"m"+secondString+"s";
    tvTimeFrom.setText(time);
}

这是我的活动

public class DatePickerActivity extends AppCompatActivity {
private static final String TAG = "DatePickerActivity";
ViewPager viewPager;
PickerAdapter adapter;
String myString = "TEST";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.date_fragment);
    String strObj = getIntent().getStringExtra("Location");
    GetParamsClass getParamsClass = new Gson().fromJson(strObj,GetParamsClass.class);

    adapter = new PickerAdapter(getFragmentManager());
    viewPager = (ViewPager) findViewById(R.id.pager);
    viewPager.setAdapter(adapter);

    setSupportActionBar((Toolbar) findViewById(R.id.toolbar));
    TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(viewPager);
    for(int i=0;i<adapter.getCount();i++) tabLayout.getTabAt(i).setText(adapter.getTitle(i));



}

public String getMyData() {
    return myString;
}

class PickerAdapter extends android.support.v13.app.FragmentPagerAdapter {
    private static final int NUM_PAGES = 2;
    Fragment fragmentOne;
    Fragment fragmentTwo;

    public PickerAdapter(FragmentManager fm) {
        super(fm);
        fragmentOne = new FragmentOne();
        fragmentTwo = new FragmentTwo();
    }

    @Override
    public int getCount() {
        return NUM_PAGES;
    }

    @Override
    public Fragment getItem(int position) {
        switch(position) {
            case 0:
                return fragmentOne;
            case 1:
            default:
                return fragmentTwo;
        }
    }

    public int getTitle(int position) {
        switch(position) {
            case 0:
                return R.string.tab_title_time;
            case 1:
            default:
                return R.string.tab_title_date;
        }
    }
}
}

修改

public class DatePickerActivity extends AppCompatActivity implements  FragmentOne.OnDateTimeSelectedListener {
private static final String TAG = "DatePickerActivity";
ViewPager viewPager;
PickerAdapter adapter;

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

    adapter = new PickerAdapter(getFragmentManager(),this);
    viewPager = (ViewPager) findViewById(R.id.pager);
    viewPager.setAdapter(adapter);

    setSupportActionBar((Toolbar) findViewById(R.id.toolbar));
    TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(viewPager);
    for(int i=0;i<adapter.getCount();i++) tabLayout.getTabAt(i).setText(adapter.getTitle(i));
}

@Override
public void onDateTimeSelected(String date) {
    Log.d(TAG, "onDateTimeSelected: "+ date);
}

class PickerAdapter extends android.support.v13.app.FragmentPagerAdapter {
    private static final int NUM_PAGES = 2;
    Fragment fragmentOne;
    Fragment fragmentTwo;

    public PickerAdapter(FragmentManager fm,DatePickerActivity activity) {
        super(fm);
        fragmentOne = new FragmentOne();
        fragmentTwo = new FragmentTwo();
        fragmentOne.setOnDateTimeSelectedListener(activity);//THIS LINE GIVES ERROR

    }

    @Override
    public int getCount() {
        return NUM_PAGES;
    }

    @Override
    public Fragment getItem(int position) {
        switch(position) {
            case 0:
                return fragmentOne;
            case 1:
            default:
                return fragmentTwo;
        }
    }

    public int getTitle(int position) {
        switch(position) {
            case 0:
                return R.string.tab_title_time;
            case 1:
            default:
                return R.string.tab_title_date;
        }
    }
}

Fragment One

public class FragmentOne extends DialogFragment implements DatePickerDialog.OnDateSetListener,TimePickerDialog.OnTimeSetListener {

Button timeButtonFrom ;
Button dateButtonFrom;
TextView tvDateFrom ;
TextView tvTimeFrom ;


public interface OnDateTimeSelectedListener{
    void onDateTimeSelected(String date);
}



private OnDateTimeSelectedListener onDateTimeSelectedListener;

public void setOnDateTimeSelectedListener(OnDateTimeSelectedListener onDateTimeSelectedListener){
    this.onDateTimeSelectedListener = onDateTimeSelectedListener;
}

public OnDateTimeSelectedListener getOnDateTimeSelectedListener(){
    return onDateTimeSelectedListener;
}




public FragmentOne(){}

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

    //FROM SIDE
    timeButtonFrom = (Button)view.findViewById(R.id.time_button);
    dateButtonFrom = (Button)view.findViewById(R.id.date_button);
    tvDateFrom = (TextView)view.findViewById(R.id.time_textview);
    tvTimeFrom = (TextView)view.findViewById(R.id.date_textview);



    timeButtonFrom.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Calendar now = Calendar.getInstance();
            // TimePickerDialog tpd = TimePickerDialog.newInstance(
            TimePickerDialog tpd = TimePickerDialog.newInstance(
                    FragmentOne.this,
                    now.get(Calendar.HOUR_OF_DAY),
                    now.get(Calendar.MINUTE),true);//24H Enable, If 12 set false
            tpd.setThemeDark(true);
            tpd.enableMinutes(true);
            tpd.setTitle("Choose Time");
            tpd.setTimeInterval(1,15);//setTimeInterval to 1H and 15Min


            tpd.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialogInterface) {
                    Log.d("TimePicker", "Dialog was cancelled");
                }
            });

            tpd.show(getFragmentManager(), "ChooseTimeFrom");
        }
    });// end Button Listener FROM

    dateButtonFrom.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Calendar now = Calendar.getInstance();
            DatePickerDialog dpd = DatePickerDialog.newInstance(
                    FragmentOne.this,
                    now.get(Calendar.YEAR),
                    now.get(Calendar.MONTH),
                    now.get(Calendar.DAY_OF_MONTH)
            );
            dpd.setThemeDark(true);
            dpd.showYearPickerFirst(true);
            dpd.setTitle("Choose Date");
            dpd.show(getFragmentManager(), "ChooseDateFrom");
        }
    });//END DATEBUTTONFROM




    return  view;

}//END ONCREATEVIEW

@Override
public void onResume() {
    super.onResume();
    DatePickerDialog dpd = (DatePickerDialog) getFragmentManager().findFragmentByTag("ChooseDateFrom");
    if(dpd != null) dpd.setOnDateSetListener(this);
    TimePickerDialog tpd = (TimePickerDialog) getFragmentManager().findFragmentByTag("ChooseTimeFrom");
    if(tpd != null) tpd.setOnTimeSetListener(this);

}



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

    String date = "You picked the following date: "+year+"/"+(++monthOfYear)+"/"+dayOfMonth;
    tvDateFrom.setText(date);

    if(tvTimeFrom != null && tvTimeFrom.getText() != null && !tvTimeFrom.getText().toString().equals("")){

        String dateTimeString = date + tvTimeFrom.getText().toString();
        onDateTimeSelectedListener.onDateTimeSelected(dateTimeString);
    }


}

@Override
public void onTimeSet(RadialPickerLayout view, int hourOfDay, int minute, int second) {

    String hourString = hourOfDay < 10 ? "0"+hourOfDay : ""+hourOfDay;
    String minuteString = minute < 10 ? "0"+minute : ""+minute;
    String secondString = second < 10 ? "0"+second : ""+second;
    String time = "You picked the following time: "+hourString+"h"+minuteString+"m"+secondString+"s";
    tvTimeFrom.setText(time);

    if(tvDateFrom != null && tvDateFrom.getText() != null && !tvDateFrom.getText().toString().equals("")){

        String dateTimeString = tvDateFrom.getText().toString() + time;
        onDateTimeSelectedListener.onDateTimeSelected(dateTimeString);
    }




}
}//END FRAGMENT CLASS

4 个答案:

答案 0 :(得分:1)

Class Activity1
{
private String pickedDateValue;

public setPickedDateValue(string val)
{
pickedDateValue = val;
}
}

Class Fragment1
{
  Activity1 act1 = (Activity1)getActivity();
   act1.setPickedDateValue(pickedval)
}

// pickval是从日期/时间选择器中选取的值

答案 1 :(得分:1)

试试这个, 在FragmentOne中创建一个界面说

function handleFormSubmit() {
    var formObject = document.getElementById('text').value;
    google.script.run.withSuccessHandler(createTable).getSportData(formObject);
  }

 /**
 * Adds an html table
 */ 
 function createTable(tableData) {
  console.log("The tableData for createTable() is " + tableData);
  var table = document.createElement('table');
  var tableBody = document.createElement('tbody');

tableData.forEach(function(rowData) {
  var row = document.createElement('tr');

  rowData.forEach(function(cellData) {
    var cell = document.createElement('td');
    cell.appendChild(document.createTextNode(cellData));
    row.appendChild(cell);
  });

  tableBody.appendChild(row);
});

table.appendChild(tableBody);
document.body.appendChild(table);
}

在onDateSet(...)方法中,如果是,则检查已经选择的时间然后调用回调

public interface OnDateTimeSelectedListener{
    void onDateTimeSelected(String date, S)
}



private OnDateTimeSelectedListener onDateTimeSelectedListener;

public void setOnDateTimeSelectedListener(OnDateTimeSelectedListener onDateTimeSelectedListener){
        this.onDateTimeSelectedListener = onDateTimeSelectedListener;
}

public OnDateTimeSelectedListener getOnDateTimeSelectedListener(){
        return onDateTimeSelectedListener;
}

在onTimeSet方法中,如果是,则检查是时间,然后调用回调

if(tvTimeFrom != null && tvTimeFrom.getText() != null && !tvTimeFrom.getText().toString().trim.equals("")){

    String dateTimeString = date + tvTimeFrom.getText().toString();
    onDateTimeSelectedListener.onDateTimeSelected(dateTimeString);
}

在DatePickerActivity

更新此行:

if(tvDateFrom != null && tvDateFrom.getText() != null && !tvDateFrom.getText().toString().trim.equals("")){

    String dateTimeString = tvDateFrom.getText().toString() + time;
    onDateTimeSelectedListener.onDateTimeSelected(dateTimeString);
}

<强>更新

public class DatePickerActivity extends AppCompatActivity implements FragmentOne.OnDateTimeSelectedListener{


 // update inside

和In

   adapter = new PickerAdapter(getFragmentManager(), this);
  ....     

构造函数更新构造函数并尝试设置侦听器

<强>更新

public PickerAdapter(FragmentManager fm) 

并覆盖

public PickerAdapter(FragmentManager fm, DatePickerActivity activity) {
        super(fm);
        fragmentOne = new FragmentOne();
        fragmentTwo = new FragmentTwo();
fragmentOne.setOnDateTimeSelectedListener(activity);
    }

<强>更新

删除出错的行并添加这两个方法并尝试

void onDateTimeSelected(String datetimeString){
    //You will get DatetimeString here
    //use it

}

}

@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 {
          onDateTimeSelectedListener = (OnDateTimeSelectedListener) activity;

    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString()
                + " must implement OnHeadlineSelectedListener");
    }

参考:Communicating with Other Fragments

答案 2 :(得分:0)

如果它的父活动然后在你的片段中添加此代码。

((DatePickerActivity)getBaseActivity()).saveData();

您可以调用saveData()函数或将数据作为Bundle对象传递。在您的活动中添加保存数据。

答案 3 :(得分:0)

您应该使用Callback接口在Fragment和它的主机Activity之间进行交互。例如:

  1. 在界面中声明并使用数据进行声明,您需要将其作为参数发送给Activity

    public interface Callback {
        void onDataPicked(Data data);
    }
    
  2. 您的活动应该实现此界面。在覆盖方法中编写自己的代码。例如:

    @Override
        public void onDataPicked(Data data) {
        Intent intent = new Intent(this, AnotherActivity.class);
        intent.putExtra("some_data", data);
        startActivity(intent);
    }
    
  3. 声明Callback实例,并在Fragment的onAttach方法中获取指向Host的链接。

    private Callback mCallback;
    
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if(context instanceof Callback){
            mCallback = (Callback) context;
        }
    }
    
  4. Finnaly,当你的数据准备就绪时,调用Calback实例的方法,它将在Activity中运行

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    
    
        Button button = (Button) view.findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mCallback.onDataPicked(new Data());
            }
        });
    }
    
  5. 不要忘记在片段的onDetach()方法中将mCallback设置为null以避免内存泄漏

    @Override
    public void onDetach() {
        super.onDetach();
        mCallback = null;
    }