I am building an android application where an event is Hosted. On hosting an event, the user fills out some form.
Now for filling the data I am using dialog-box of data picker. I am able to do this in an activity but when I am implementing it in Fragmented, this code is not working.
I need to have when user clicks an image button, an dialog-box of data-picker should been displayed. Here is code:
package tabsswipe;
public class FragmentOne extends Fragment implements OnClickListener{
private ImageButton ib;
private Calendar cal;
private int day;
private int month;
private int year;
private EditText et;
private static final String TAG = FragmentOne.class.getSimpleName();
Calendar c = Calendar.getInstance();
int startYear = c.get(Calendar.YEAR);
int startMonth = c.get(Calendar.MONTH);
int startDay = c.get(Calendar.DAY_OF_MONTH);
Spinner spnr;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_play, container, false);
ImageButton btnhost = (ImageButton) getActivity().findViewById(R.id.hostbutton);
btnhost.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
viewCategory();
}
});
return rootView;
}
private void viewCategory() {
AlertDialog.Builder viewDialog = new AlertDialog.Builder(getActivity());
viewDialog.setTitle("Event");
LayoutInflater li = (LayoutInflater)
getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View dialogView = li.inflate(R.layout.customealertdialogbox, null);
viewDialog.setView(dialogView);
viewDialog.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
});
viewDialog.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
});
ib = (ImageButton) dialogView.findViewById(R.id.imageButton1);
cal = Calendar.getInstance();
day = cal.get(Calendar.DAY_OF_MONTH);
month = cal.get(Calendar.MONTH);
year = cal.get(Calendar.YEAR);
et = (EditText) dialogView.findViewById(R.id.editText);
ib.setOnClickListener(this);
viewDialog.show();
}
@Override
public void onClick(View v) {
showDialog(0);
}
private DatePickerDialog showDialog(int i) {
// TODO Auto-generated method stub
return new DatePickerDialog(getActivity(), datePickerListener, year, month, day);
}
private DatePickerDialog.OnDateSetListener datePickerListener = new
DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int selectedYear,
int selectedMonth, int selectedDay) {
et.setText(selectedDay + " / " + (selectedMonth + 1) + " / "
+ selectedYear);
}
};
}
Just call dailog datapicker fragment in your image button directly.
Here I had code as per your question.