Display TimePicker when textField is focused - java

I am just getting into android apps and now trying to work with an interface that allows the user to enter time into a text box. The time picker dialog will display when a text box is focused. But now when I click the text box, the date picker dialog does not display.
WorkDetails.java
public void onFocusChange(View v, boolean hasFocus) {
EditText txtTime = (EditText) findViewById(R.id.editText6);
txtTime.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus)
{
TimePick time = new TimePick(v);
FragmentTransaction ft = getFragmentManager().beginTransaction();
time.show(ft, "TimePicker");
}
}
});
}
TimePick.java
#SuppressLint("ValidFragment")
public class TimePick extends DialogFragment implements TimePickerDialog.OnTimeSetListener {
private TextView time;
public TimePick(View view)
{
time=(EditText)view;
}
public Dialog onCreateDialog(Bundle savedInstanceState)
{
final Calendar c= Calendar.getInstance();
int hour=c.get(Calendar.HOUR_OF_DAY);
int minute=c.get(Calendar.MINUTE);
//Toast.makeText(getActivity(),this,"Date: "+year+"-",+month+"-"+day,Toast.LENGTH_SHORT).show();
return new TimePickerDialog(getActivity(),this,hour,minute, DateFormat.is24HourFormat(getActivity()));
}
public void onTimeSet(TimePicker view,int hourofDay, int minute)
{
time.setText(Integer.toString(hourofDay) + ":" + Integer.toString(minute));
}
}

editText = (EditText)findViewById(R.id.editText);
editText2 = (EditText)findViewById(R.id.editText2);
editText3 = (EditText)findViewById(R.id.editText3);
editText2.setOnFocusChangeListener(new View.OnFocusChangeListener()
{
#Override
public void onFocusChange(View v, boolean hasFocus)
{
String input;
EditText editText;
if(!hasFocus)
{
TimePick time = new TimePick(v);
FragmentTransaction ft = getFragmentManager().beginTransaction();
time.show(ft, "TimePicker");
}
}
});
editText2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TimePick time = new TimePick(v);
FragmentTransaction ft = getFragmentManager().beginTransaction();
time.show(ft, "TimePicker");
}
});
}
public class TimePick extends DialogFragment implements TimePickerDialog.OnTimeSetListener
{
private TextView time;
public TimePick(View view)
{
time=(EditText)view;
}
public Dialog onCreateDialog(Bundle savedInstanceState)
{
final Calendar c= Calendar.getInstance();
int hour=c.get(Calendar.HOUR_OF_DAY);
int minute=c.get(Calendar.MINUTE);
//Toast.makeText(getActivity(),this,"Date: "+year+"-",+month+"-"+day,Toast.LENGTH_SHORT).show();
return new TimePickerDialog(getActivity(),this,hour,minute, DateFormat.is24HourFormat(getActivity()));
}
public void onTimeSet(TimePicker view,int hourofDay, int minute)
{
time.setText(Integer.toString(hourofDay) + ":" + Integer.toString(minute));
}
}

try to set android:clickable="true" and android:focusableInTouchMode="false" in xml file.

Related

Opening AlertDialog inside Dialog Fragment

I have a custom Dialog Fragment and I need to display an Alert dialog inside it.
Is it possible to do without closing the Dialog fragment?
When I do it with the context provided for the Dialog fragment it just closes the Dialog fragment and open the Alert dialog.
case R.id.deleteButton:
new AlertDialog.Builder(context)
.setTitle(context.getResources().getString(R.string.discard_changes))
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton(android.R.string.yes, (dialog, whichButton) -> {
onItemClickListener.onItemClick(Device, DELETE_DOC);
dismiss();
})
.setNegativeButton(android.R.string.no, null).show();
break;
EDIT
As requested, the whole Dialog code:
public class InstallationDocumentDeviceAddFormDialog extends Dialog implements View.OnClickListener {
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager layoutManager;
private Context context;
private Button btn_cancel;
NavBar navBar;
Button addDeviceButton;
ImageButton deleteButton;
boolean isEditMode;
public static int EDIT_INSTALLATIONDOC = 1;
public static int DELETE_INSTALLATIONDOC = 2;
private InstallationDocumentDevice installationDocumentDevice;
public interface OnItemClickListener {
void onItemClick(InstallationDocumentDevice installationDocumentDevice, int action);
}
#NonNull
private OnItemClickListener onItemClickListener;
public InstallationDocumentDeviceAddFormDialog(#NonNull Context context, InstallationDocumentDevice installationDocumentDevice, boolean isEditMode, #NonNull OnItemClickListener onItemClickListener) {
super(context);
this.context = context;
this.onItemClickListener = onItemClickListener;
this.installationDocumentDevice = installationDocumentDevice;
this.isEditMode = isEditMode;
Log.i("DocumentController", "dialog device: " + installationDocumentDevice.toString());
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_new_device_form);
RecyclerView accessoriesRecyclerView = (RecyclerView) findViewById(R.id.addNewDeviceAccessoriesRecycler);
RecyclerView guidancesRecyclerView = (RecyclerView) findViewById(R.id.addNewDeviceGuidancesRecycler);
RecyclerView testsRecyclerView = (RecyclerView) findViewById(R.id.addNewDeviceTestsRecycler);
navBar = findViewById(R.id.navBar);
if(isEditMode) navBar.setTitle(context.getResources().getString(R.string.editing_device) + " " + installationDocumentDevice.getLocalizedDeviceName());
else navBar.setTitle(context.getResources().getString(R.string.adding_new_device) + " " + installationDocumentDevice.getLocalizedDeviceName());
addDeviceButton = findViewById(R.id.btnAddNewDevice);
addDeviceButton.setOnClickListener(this);
deleteButton = (ImageButton) findViewById(R.id.deleteButton);
if(isEditMode){
deleteButton.setVisibility(View.VISIBLE);
deleteButton.setOnClickListener(this);
addDeviceButton.setText(context.getResources().getString(R.string.add_new_device_title));
} else {
deleteButton.setVisibility(View.GONE);
}
// navBar.getBackButton().setOnClickListener(view -> dismiss());
accessoriesRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
guidancesRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
testsRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
accessoriesRecyclerView.setAdapter(new InstallationDocumentDeviceAddFormAdapter(installationDocumentDevice, this::onClick, InstallationDocumentDeviceAddFormAdapter.ACCESSORIES));
guidancesRecyclerView.setAdapter(new InstallationDocumentDeviceAddFormAdapter(installationDocumentDevice, this::onClick, InstallationDocumentDeviceAddFormAdapter.GUIDANCES));
testsRecyclerView.setAdapter(new InstallationDocumentDeviceAddFormAdapter(installationDocumentDevice, this::onClick, InstallationDocumentDeviceAddFormAdapter.TESTS));
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnAddNewDevice:
onItemClickListener.onItemClick(installationDocumentDevice, EDIT_INSTALLATIONDOC);
dismiss();
break;
case R.id.deleteButton:
new AlertDialog.Builder(context)
.setTitle(context.getResources().getString(R.string.datapick_discard_changes))
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton(android.R.string.yes, (dialog, whichButton) -> {
onItemClickListener.onItemClick(installationDocumentDevice, DELETE_INSTALLATIONDOC);
dismiss();
})
.setNegativeButton(android.R.string.no, null).show();
// onItemClickListener.onItemClick(installationDocumentDevice, DELETE_INSTALLATIONDOC);
// dismiss();
break;
}
dismiss();
}
private void onClick(int position, int tag) {
switch (tag) {
//Case Accessory
case 1:
// Toast.makeText(context, "Accessory pos: " + position + ". Is checked: " + installationDocumentDevice.getAccessories().get(position).isChecked(), Toast.LENGTH_SHORT).show();
break;
//Case Guidance
case 2:
// Toast.makeText(context, "Guidances pos: " + position, Toast.LENGTH_SHORT).show();
break;
//Case Tests
case 3:
// Toast.makeText(context, "Tests pos: " + position, Toast.LENGTH_SHORT).show();
break;
}
}
}
/* Yes This is Possible You Can Grow through Below My Code which I Use In Recycler Adapter in Holder View Click Event.*/
holder.calendar_day_gridcell.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v1) {
// holder.txt_InTime.setText("Helllo");
try {
// Date parsedDate = dateFormatter.parse(date_month_year);
//Log.d(tag, "Parsed Date: " + parsedDate.toString());
DoubleClickPerform.preventTwoClick(v1);
final Dialog dialog = new Dialog(context,R.style.Theme_AppCompat_Dialog_Alert);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
Calendar calendar;
int currentHour;
int currentMinute;
TextView txt_dialog_InTime,txt_dialog_OutTime,txt_dialog_SaveInTime,/*txt_dialog_Delete_InTime*/txt_dialog_SaveOutTime/*txt_dialog_Delete_OutTime*/;
ImageView img_clean_in_time,img_clean_out_time;
Button btn_close;
View view1 = context.getLayoutInflater().inflate(R.layout.in_out_time_dialog, null);
txt_dialog_InTime = view1.findViewById(R.id.txt_dialog_InTime);
txt_dialog_OutTime = view1.findViewById(R.id.txt_dialog_OutTime);
txt_dialog_SaveInTime = view1.findViewById(R.id.txt_dialog_SaveInTime);
// txt_dialog_Delete_InTime = view1.findViewById(R.id.txt_dialog_Delete_InTime);
txt_dialog_SaveOutTime = view1.findViewById(R.id.txt_dialog_SaveOutTime);
// txt_dialog_Delete_OutTime = view1.findViewById(R.id.txt_dialog_Delete_OutTime);
img_clean_in_time = view1.findViewById(R.id.img_clean_in_time);
img_clean_out_time = view1.findViewById(R.id.img_clean_out_time);
btn_close = view1.findViewById(R.id.btn_close);
calendar = Calendar.getInstance();
currentHour = calendar.get(Calendar.HOUR_OF_DAY);
currentMinute = calendar.get(Calendar.MINUTE);
txt_dialog_InTime.setText(holder.txt_InTime.getText().toString());
if(txt_dialog_InTime.getText().toString().equals(""))
{
txt_dialog_OutTime.setEnabled(false);
}
else
{
txt_dialog_OutTime.setEnabled(true);
}
btn_close.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
txt_dialog_InTime.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TimePickerDialog timePickerDialog= new TimePickerDialog(context,
new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker timePicker, int hour, int minute) {
Time time = new Time(hour, minute, 0);
//little h uses 12 hour format and big H uses 24 hour format
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("hh:mm aa");
//format takes in a Date, and Time is a sublcass of Date
String s = simpleDateFormat.format(time);
txt_dialog_InTime.setText(s);
}
}, currentHour, currentMinute, false);
timePickerDialog.show();
}
});
dialog.setContentView(view1);
dialog.show();
img_clean_in_time.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
txt_dialog_InTime.setText("");
}
});
img_clean_out_time.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
txt_dialog_OutTime.setText("");
}
});
txt_dialog_OutTime.setText(holder.txt_OutTime.getText().toString());
txt_dialog_OutTime.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TimePickerDialog timePickerDialog= new TimePickerDialog(context,
new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker timePicker, int hour, int minute) {
Time time = new Time(hour, minute, 0);
//little h uses 12 hour format and big H uses 24 hour format
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("hh:mm aa");
//format takes in a Date, and Time is a sublcass of Date
String s = simpleDateFormat.format(time);
txt_dialog_OutTime.setText(s);
}
}, currentHour, currentMinute, false);
timePickerDialog.show();
}
});
dialog.setContentView(view1);
dialog.show();
/* txt_dialog_Delete_InTime.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
holder.txt_InTime.setText("");
dialog.dismiss();
}
});
txt_dialog_Delete_OutTime.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
holder.txt_OutTime.setText("");
dialog.dismiss();
}
});
*/
txt_dialog_SaveInTime.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
holder.txt_InTime.setText(txt_dialog_InTime.getText().toString());
apiforSaveTime(txt_dialog_InTime.getText().toString(),txt_dialog_OutTime.getText().toString(), finalRevereseDate);
dialog.dismiss();
}
});
txt_dialog_SaveOutTime.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
holder.txt_OutTime.setText(txt_dialog_OutTime.getText().toString());
if(!txt_dialog_InTime.getText().toString().equals(""))
{
apiforSaveTime(txt_dialog_InTime.getText().toString(),txt_dialog_OutTime.getText().toString(), finalRevereseDate);
dialog.dismiss();
}
else
{
Snackbar snackbar = Snackbar
.make(holder.itemView, "In Time Is Required", Snackbar.LENGTH_LONG);
snackbar.show();
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
});

how to call dialog fragment with listview and search filter from a fragment and save selected item value in parent fragment as string?

public class fragment_oneway_flight extends Fragment {
private Spinner spinner1 ;
Context thiscontext;
private int mYear, mMonth, mDay, mHour, mMinute;
int countadult= 1;
int countchild= 0;
int countinfant= 0;
private ProgressDialog pDialog,pDialog1;
TextView quantity_adult_textview, quantity_child_textview, quantity_infant_textview, textview_city_slct_from_oneway, textview_city_slct_to_oneway;
private ImageButton increment_adult_Button, decrement_adult_Button, increment_child_Button, decrement_child_Button, increment_infant_Button, decrement_infant_Button;
private Button prcdtoonwyrslt;
public fragment_oneway_flight() {
// Required empty public constructor
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
thiscontext = container.getContext();
View rootView = inflater.inflate(R.layout.fragment_oneway_flight, container, false);
LinearLayout select_dep_date = (LinearLayout) rootView.findViewById(R.id.date_from_select_oneway);
select_dep_date.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DialogFragment dFragment = new DatePickerFragment();
// Show the date picker dialog fragment
dFragment.show(getFragmentManager(), "Date Picker");
}
});
LinearLayout city_slct_from_oneway = (LinearLayout) rootView.findViewById(R.id.city_slct_from_oneway);
city_slct_from_oneway.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DialogBoxFragment DialogBoxFragment = new DialogBoxFragment ();
DialogBoxFragment.show(getFragmentManager(),"dialog");
}
});
LinearLayout city_slct_to_oneway = (LinearLayout) rootView.findViewById(R.id.city_slct_to_oneway);
city_slct_to_oneway.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DialogBoxFragment2 DialogBoxFragment2 = new DialogBoxFragment2 ();
DialogBoxFragment2.show(getFragmentManager(),"dialog2");
}
});
prcdtoonwyrslt = (Button) rootView.findViewById( R.id.prcdtoonwyrslt );
prcdtoonwyrslt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), activity_flight_result_oneway.class);
pDialog1 = new ProgressDialog(getActivity());
pDialog1.setMessage("Please Wait...");
pDialog1.setCancelable(false);
String countadult = quantity_adult_textview.getText().toString();
String countchild = quantity_child_textview.getText().toString();
String countinfant = quantity_infant_textview.getText().toString();
String selectedfromcity = textview_city_slct_from_oneway.getText().toString();
String selectedtocity = textview_city_slct_to_oneway.getText().toString();
intent.putExtra("adultsnos", countadult);
intent.putExtra("childsnos", countchild);
intent.putExtra("infantsnos", countinfant);
intent.putExtra("fromcity", selectedfromcity);
intent.putExtra("tocity", selectedtocity);
startActivity(intent);
}
});
// button function start
increment_adult_Button = (ImageButton) rootView.findViewById( R.id.increment_adult_Button );
decrement_adult_Button = (ImageButton) rootView.findViewById( R.id.decrement_adult_Button );
increment_child_Button = (ImageButton) rootView.findViewById( R.id.increment_child_Button );
decrement_child_Button = (ImageButton) rootView.findViewById( R.id.decrement_child_Button );
increment_infant_Button = (ImageButton) rootView.findViewById( R.id.increment_infant_Button );
decrement_infant_Button = (ImageButton) rootView.findViewById( R.id.decrement_infant_Button );
quantity_adult_textview = (TextView) rootView.findViewById(R.id.quantity_adult_textview);
quantity_child_textview = (TextView) rootView.findViewById(R.id.quantity_child_textview);
quantity_infant_textview = (TextView) rootView.findViewById(R.id.quantity_infant_textview);
increment_adult_Button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
countadult++;
if(countadult>7){
countadult=7;
}
display(countadult);
}
});
decrement_adult_Button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
countadult--;
if(countadult<1){
countadult=1;
}
display(countadult);
}
});
increment_child_Button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
countchild++;
if(countchild>5){
countchild=5;
}
display(countchild);
}
});
decrement_child_Button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
countchild--;
if(countchild<0){
countchild=0;
}
display(countchild);
}
});
increment_infant_Button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
countinfant++;
if(countinfant>5){
countinfant=5;
}
display(countinfant);
}
});
decrement_infant_Button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
countinfant--;
if(countinfant<0){
countinfant=0;
}
display(countinfant);
}
});
// button function end
setSpinnerContent( rootView );
spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> id, View rootView, int pos, long arg3) {
if (pos == 0) {
Toast.makeText(getActivity().getApplicationContext(),
"Select Class", Toast.LENGTH_SHORT)
.show();
} else if (pos == 1) {
Toast.makeText(getActivity().getApplicationContext(),
"You have selected Economy", Toast.LENGTH_SHORT)
.show();
} else if (pos == 2) {
Toast.makeText(getActivity().getApplicationContext(),
"You have selected Premium Economy", Toast.LENGTH_SHORT)
.show();
} else if (pos == 3) {
Toast.makeText(getActivity().getApplicationContext(),
"You have selected Business", Toast.LENGTH_SHORT)
.show();
}else if (pos == 4) {
Toast.makeText(getActivity().getApplicationContext(),
"You have selected First Class", Toast.LENGTH_SHORT)
.show();
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
Toast.makeText(getActivity().getApplicationContext(), "Nothing to select", Toast.LENGTH_LONG).show();
}
});
return rootView;
}
private void setSpinnerContent( View rootView ) {
spinner1 = (Spinner) rootView.findViewById( R.id.spinner_flight );
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(), R.array.flight_class_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter( adapter );
}
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);
/*
Initialize a new DatePickerDialog
DatePickerDialog(Context context, DatePickerDialog.OnDateSetListener callBack,
int year, int monthOfYear, int dayOfMonth)
*/
DatePickerDialog dpd = new DatePickerDialog(getActivity(), R.style.DateDialog,this,year,month,day);
return dpd;
}
public void onDateSet(DatePicker view, int year, int month, int day){
// Do something with the chosen date
TextView dep_date_flight = (TextView) getActivity().findViewById(R.id.text_dep_date);
// 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
dep_date_flight.setText(formattedDate);
}
}
private void display(int number) {
quantity_adult_textview.setText(String.valueOf(countadult));
quantity_child_textview.setText(String.valueOf(countchild));
quantity_infant_textview.setText(String.valueOf(countinfant));
}
public static class DialogBoxFragment extends DialogFragment {
//declaring variables
private ListView listviewforresults;
//Adapter for listview
ArrayAdapter<String> list1adapter;
//Edittext for search
EditText searchdata;
//ArrayList for listview
ArrayList<String> data=new ArrayList<String>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View rootView1 = inflater.inflate(R.layout.fragment_city_select_flight, container, false);
prepareDummyData();
listviewforresults=(ListView)rootView1.findViewById(R.id.showdata);
searchdata=(EditText)rootView1.findViewById(R.id.searchdata);
//set data to Adapter
list1adapter=new ArrayAdapter<String>(getActivity(), country_list,R.id.results,data);
listviewforresults.setAdapter(list1adapter);
//search data when text changes in edittext
searchdata.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
list1adapter.getFilter().filter(s);
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
listviewforresults.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
String selectedFromList = (String) listviewforresults.getItemAtPosition(position).toString();
TextView textview_city_slct_from_oneway = (TextView) getActivity().findViewById(R.id.textview_city_slct_from_oneway);
textview_city_slct_from_oneway.setText(selectedFromList);
getDialog().dismiss();
}
});
getDialog().setTitle("dialog");
return rootView1;
}
public void prepareDummyData()
{
data.add("Chennai");
data.add("Mumbai");
data.add("Bangalore");
data.add("Madurai");
data.add("Coimbatore");
data.add("Newdelhi");
}
}
public static class DialogBoxFragment2 extends DialogFragment {
//declaring variables
private ListView listviewforresults2;
//Adapter for listview
ArrayAdapter<String> list2adapter;
//Edittext for search
EditText searchdata;
//ArrayList for listview
ArrayList<String> data=new ArrayList<String>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View rootView2 = inflater.inflate(R.layout.fragment_city_select_flight2, container, false);
prepareDummyData2();
listviewforresults2=(ListView)rootView2.findViewById(R.id.showdata);
searchdata=(EditText)rootView2.findViewById(R.id.searchdata);
//set data to Adapter
list2adapter=new ArrayAdapter<String>(getActivity(), country_list,R.id.results,data);
listviewforresults2.setAdapter(list2adapter);
//search data when text changes in edittext
searchdata.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
list2adapter.getFilter().filter(s);
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
listviewforresults2.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
String selectedFromList2 = (String) listviewforresults2.getItemAtPosition(position).toString();
TextView textview_city_slct_to_oneway = (TextView) getActivity().findViewById(R.id.textview_city_slct_to_oneway);
textview_city_slct_to_oneway.setText(selectedFromList2);
getDialog().dismiss();
}
});
getDialog().setTitle("dialog2");
return rootView2;
}
public void prepareDummyData2() {
data.add("Chennai");
data.add("Mumbai");
data.add("Bangalore");
data.add("Madurai");
data.add("Coimbatore");
data.add("Newdelhi");
}
}
}
the above code is full fragment code with gialog innerclass too. im a beginner can you gys help me out of it?
and actually what i need is i have to click the from and to area in tab view fragment. after slecting it opens a dialog with search filter and listview. after clicking any list item it should diaplay in textview on parent fragment and after that i should be able wo pass the value to next fragment using put intent method.
currently im getting null value when i pass it to the next fragment.
i dont know why.
i have attached an image to get you the clear view. please check it.see here

I need to create a first and last button for my ViewPager

Hello need help with a class trying to figure out how to create a first and last button in a fragment that will jump to the first item in a ViewPager and the last item in a ViewPager I'm a bit lost with how to implement. Here is the fragment.
public class CrimeFragment extends Fragment {
private static final String ARG_CRIME_ID = "crime_id";
private static final String DIALOG_DATE = "DialogDate";
private static final int REQUEST_DATE = 0;
private Crime mCrime;
private EditText mTitleField;
private Button mDateButton;
private CheckBox mSolvedCheckBox;
private Spinner mSpinner;
private Button mFirstButton;
private Button mLastButton;
public static CrimeFragment newInstance(UUID crimeId) {
Bundle args = new Bundle();
args.putSerializable(ARG_CRIME_ID, crimeId);
CrimeFragment fragment = new CrimeFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != Activity.RESULT_OK) {
return;
}
if (requestCode == REQUEST_DATE) {
Date date =
(Date) data.getSerializableExtra(DatePickerFragment.EXTRA_DATE);
mCrime.setDate(date);
updateDate();
}
}
private void updateDate() {
mDateButton.setText(mCrime.getDate().toString());
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
UUID crimeId = (UUID) getArguments().getSerializable(ARG_CRIME_ID);
mCrime = CrimeLab.get(getActivity()).getCrime(crimeId);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_crime, container, false);
mTitleField = (EditText)v.findViewById(R.id.crime_title);
mTitleField.setText(mCrime.getTitle());
mTitleField.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(
CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(
CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
mDateButton = (Button) v.findViewById(R.id.crime_date);
updateDate();
mDateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager manager = getFragmentManager();
DatePickerFragment dialog = DatePickerFragment.newInstance(mCrime.getDate());
dialog.setTargetFragment(CrimeFragment.this, REQUEST_DATE);
dialog.show(manager, DIALOG_DATE);
}
});
mSpinner = (Spinner) v.findViewById(R.id.crime_severity);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this.getActivity(),
R.array.severity_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mSpinner.setAdapter(adapter);
mSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
mCrime.setSeverity((String) mSpinner.getSelectedItem());
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
}
});
mSolvedCheckBox = (CheckBox) v.findViewById(R.id.crime_solved);
mSolvedCheckBox.setChecked(mCrime.isSolved());
mSolvedCheckBox.setOnCheckedChangeListener(
new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
mCrime.setSolved(isChecked);
}
});
mFirstButton = (Button) v.findViewById(R.id.first_crime_button);
mFirstButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
mLastButton = (Button) v.findViewById(R.id.last_crime_button);
mLastButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
return v;
}
}
Here is the Activity with the ViewPager.
public class CrimePagerActivity extends FragmentActivity{
private static final String EXTRA_CRIME_ID = "com.martin.android.criminalintent.crime_id";
private ViewPager mViewPager;
private List<Crime> mCrimes;
public static Intent newIntent(Context packageContext, UUID crimeId) {
Intent intent = new Intent(packageContext, CrimePagerActivity.class);
intent.putExtra(EXTRA_CRIME_ID, crimeId);
return intent;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_crime_pager);
UUID crimeId = (UUID) getIntent().getSerializableExtra(EXTRA_CRIME_ID);
mViewPager = (ViewPager) findViewById(R.id.activity_crime_pager_view_pager);
mCrimes = CrimeLab.get(this).getCrimes();
FragmentManager fragmentManager = getSupportFragmentManager();
mViewPager.setAdapter(new FragmentStatePagerAdapter(fragmentManager) {
#Override
public Fragment getItem(int position) {
Crime crime = mCrimes.get(position);
return CrimeFragment.newInstance(crime.getId());
}
#Override
public int getCount() {
return mCrimes.size();
}
});
for (int i = 0; i < mCrimes.size(); i++) {
if (mCrimes.get(i).getId().equals(crimeId)) {
mViewPager.setCurrentItem(i);
break;
}
}
}
}
For the First button Im pretty sure I just need to set item to 0? For last button I need to set item to size - 1 just not sure how to do that.
In your CrimePagerActivity, write two method's to jump to the ViewPager first page and last page.
CrimePagerActivity.java:
public void jumpToFirstPage() {
mViewPager.setCurrentItem(0);
}
public void jumpToLastPage() {
mViewPager.setCurrentItem(mCrimes.size() - 1);
}
Call those method's from mFirstButton and mLastButton click listener method:
CrimeFragment.java:
mFirstButton = (Button) v.findViewById(R.id.first_crime_button);
mFirstButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((CrimePagerActivity)getActivity()).jumpToFirstPage();
}
});
mLastButton = (Button) v.findViewById(R.id.last_crime_button);
mLastButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((CrimePagerActivity)getActivity()).jumpToLastPage();
}
});
Hope this will work perfectly.
Ok this was a answer that I was given by the teacher incase anyone is interested.
mFirstButton = (Button) v.findViewById(R.id.first_crime_button);
mFirstButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ViewPager pager = (ViewPager) getActivity().findViewById(R.id.activity_crime_pager_view_pager);
pager.setCurrentItem(0);
}
});
mLastButton = (Button) v.findViewById(R.id.last_crime_button);
mLastButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ViewPager pager = (ViewPager) getActivity().findViewById(R.id.activity_crime_pager_view_pager);
pager.setCurrentItem(CrimeLab.get(getActivity()).getCrimes().size()-1);
}
});
Create two button and on click set
viewPager.setCurrentItem(0); // for top
and
viewPager.setCurrentItem(mCrimes.size()); // for last

showDialog not displayed Android

Inside an Activity, I am calling different fragments , I want the user to be able to change the date by clicking on a textView that displays the current date, the showDialog does not want to be displayed.
dateView.setOnClickListener(new View.OnClickListener() {
#SuppressWarnings("deprecation")
public void onClick(View v) {
getActivity().showDialog(999);
}
});
Android Studio tells me that CreateDialog is never used.
protected Dialog onCreateDialog(int id) {
// TODO Auto-generated method stub
if (id == 999) {
return new DatePickerDialog(getContext(),
myDateListener, year, month, day);
}
return null;
}
Full code:
public class Fragment5 extends android.support.v4.app.Fragment {
private DatePicker datePicker;
private Calendar calendar;
private TextView dateView;
TimePicker timePicker2;
private int year, month, day;
public Fragment5() {
}
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_fragment5, container, false);
dateView = (TextView) rootView.findViewById(R.id.textView3);
calendar = Calendar.getInstance();
year = calendar.get(Calendar.YEAR);
month = calendar.get(Calendar.MONTH);
day = calendar.get(Calendar.DAY_OF_MONTH);
showDate(year, month+1, day);
dateView.setOnClickListener(new View.OnClickListener() {
#SuppressWarnings("deprecation")
public void onClick(View v) {
getActivity().showDialog(999);
}
});
return rootView;
}
protected Dialog onCreateDialog(int id) {
// TODO Auto-generated method stub
if (id == 999) {
return new DatePickerDialog(getContext(),
myDateListener, year, month, day);
}
return null;
}
private DatePickerDialog.OnDateSetListener myDateListener = new
DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker arg0,
int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
// arg1 = year
// arg2 = month
// arg3 = day
showDate(arg1, arg2+1, arg3);
}
};
private void showDate(int year, int month, int day) {
dateView.setText(new StringBuilder().append(day).append("/")
.append(month).append("/").append(year));
}
}
MainActivity
public class MainActivity extends AppCompatActivity {
public static Bundle myBundl = new Bundle();
private List<ItemSlideMenu> listSliding;
private SlidingMenuAdapter3 adapter;
private Calendar calendar;
private TextView dateView;
TimePicker timePicker2;
final Context context = this ;
private int year, month, day;
private ListView listViewSliding;
private DrawerLayout drawerLayout;
private ActionBarDrawerToggle actionBarDrawerToggle;
String name1;
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
calendar = Calendar.getInstance();
year = calendar.get(Calendar.YEAR);
month = calendar.get(Calendar.MONTH);
day = calendar.get(Calendar.DAY_OF_MONTH);
showDate(year, month+1, day);
//Init component
listViewSliding = (ListView) findViewById(R.id.lv_sliding_menu);
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
listSliding = new ArrayList<>();
//Add item for sliding list
listSliding.add(new ItemSlideMenu(R.drawable.home_96,"Accueil" ));
listSliding.add(new ItemSlideMenu(R.drawable.cocktail,"Organiser une Sortie"));
listSliding.add(new ItemSlideMenu(R.drawable.geo,"Autour de moi"));
listSliding.add(new ItemSlideMenu(R.drawable.ami,"Liste d'amis" ));
listSliding.add(new ItemSlideMenu(R.drawable.message,"Contact"));
listSliding.add(new ItemSlideMenu(R.drawable.information,"Credits"));
adapter = new SlidingMenuAdapter3(this, listSliding);
listViewSliding.setAdapter(adapter);
//Display icon to open/ close sliding list
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//Set title
setTitle(listSliding.get(0).getTitle());
//item selected
listViewSliding.setItemChecked(0, true);
//Close menu
drawerLayout.closeDrawer(listViewSliding);
//Display fragment 1 when start
replaceFragment(0);
//Hanlde on item click
listViewSliding.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Set title
setTitle(listSliding.get(position).getTitle());
//item selected
listViewSliding.setItemChecked(position, true);
if (position==2){
Intent i2 = new Intent(getApplicationContext(), MapsActivity.class);
startActivity(i2);
} else
{//Replace fragment
replaceFragment(position);
}//Close menu
drawerLayout.closeDrawer(listViewSliding);
}
});
actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.drawer_opened, R.string.drawer_closed){
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
invalidateOptionsMenu();
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
invalidateOptionsMenu();
}
};
drawerLayout.setDrawerListener(actionBarDrawerToggle);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(actionBarDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
actionBarDrawerToggle.syncState();
}
//Create method replace fragment
private void replaceFragment(int pos) {
android.support.v4.app.Fragment fragment = null;
switch (pos) {
case 0:
fragment = new Fragment1();
break;
case 1:
fragment = new Fragment2();
break;
case 2:
fragment = new Fragment3();
break;
case 3 :
fragment = new Fragment4();
break;
}
if(null!=fragment) {
android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
android.support.v4.app.FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.main_content,fragment);
transaction.addToBackStack(null);
transaction.commit();
}
}
#SuppressWarnings("deprecation")
protected Dialog onCreateDialog(int id) {
// TODO Auto-generated method stub
if (id == 999) {
return new DatePickerDialog(this,
myDateListener, year, month, day);
}
else if (id ==98) {
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.custom);
dialog.setTitle("Title...");
// set the custom dialog components - text, image and button
Button dialogButton = (Button) dialog.findViewById(R.id.dialogButtonOK);
dialogButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment6 fragment = null;
fragment = new Fragment6();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.contact, fragment);
transaction.addToBackStack(null);
transaction.commit();
dialog.dismiss();
}
});
dialog.show();
// if button is clicked, close the custom dialog
}
return null;
}
private DatePickerDialog.OnDateSetListener myDateListener = new
DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker arg0,
int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
// arg1 = year
// arg2 = month
// arg3 = day
showDate(arg1, arg2+1, arg3);
}
};
private void showDate(int year, int month, int day) {
StringBuilder abbes = new StringBuilder().append(day).append("/")
.append(month).append("/").append(year);
Bundle bundle = new Bundle();
bundle.putString("edttext", String.valueOf(abbes));
// set Fragmentclass Arguments
Fragment5 fragobj = new Fragment5();
fragobj.setArguments(bundle);
}
}
Since,
Callback for creating dialogs that are managed (saved and restored) for you by the Activity.
Implement this method in Activityinstead of Fragment
#Override
protected Dialog onCreateDialog(int id) {
// TODO Auto-generated method stub
if (id == 999) {
return new DatePickerDialog(getContext(),
myDateListener, year, month, day);
}
return null;
}
Call Fragment like this;
private void showDate(int year, int month, int day) {
StringBuilder abbes = new StringBuilder().append(day).append("/")
.append(month).append("/").append(year);
if(fragment instanceof Fragment4){
((Fragemnt4)fragment).dateView.setText(""+abbes);
}
}
Make dateView public
showDialog() is deprecated. Replace this code
public class Fragment5 extends android.support.v4.app.Fragment {
private DatePicker datePicker;
private Calendar calendar;
private TextView dateView;
TimePicker timePicker2;
private int year, month, day;
DialogFragment dateFragment;
public Fragment5() {
}
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_fragment5, container, false);
dateView = (TextView) rootView.findViewById(R.id.textView3);
calendar = Calendar.getInstance();
year = calendar.get(Calendar.YEAR);
month = calendar.get(Calendar.MONTH);
day = calendar.get(Calendar.DAY_OF_MONTH);
showDate(year, month+1, day);
dateView.setOnClickListener(new View.OnClickListener() {
#SuppressWarnings("deprecation")
public void onClick(View v) {
dateFragment = new DatePickerFragment();
dateFragment.show(getFragmentManager(), "datePicker");
}
});
return rootView;
}
private void showDate(int year, int month, int day) {
dateView.setText(new StringBuilder().append(day).append("/")
.append(month).append("/").append(year));
}
class DatePickerFragment extends DialogFragment implements
DatePickerDialog.OnDateSetListener {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), this, year, month, day);
}
public void onDateSet(DatePicker view, int year, int month, int day) {
showDate(year,month,day);
}
} }
What exactly showDialog (int id) method does is show a dialog managed by activity. A call to onCreateDialog(int, Bundle) will be made with the same id the first time this is called for a given id. From thereafter, the dialog will be automatically saved and restored.
You must write your onCreateDialog method in Activity as said by #Burhanuddin Rashid but that could cause complexity in data transition between Activity and Fragment.
Further,
void showDialog (int id)
This method was deprecated in API level 13.
Use the new DialogFragment class with FragmentManager instead; this is also available on older platforms through the Android compatibility package.
PS,
I recommend you to use a DialogFragment
For more info check out this official documentation

TimePicker Dialog

I'm using multiple textviews with onclick listeners that direct me to a TimePicker Dialog.
However I cannot seem to know how to write the code after reading the tutorials,
textview1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
showDialog(TIME_DIALOG_ID);
}
});
textview2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
showDialog(TIME_DIALOG_ID);
}
});
To show the dialog:
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case TIME_DIALOG_ID:
return new TimePickerDialog(this,
mTimeSetListener, mHour, mMinute, true);
}
return null;
}
and finally,
private TimePickerDialog.OnTimeSetListener mTimeSetListener =
new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(android.widget.TimePicker view,
int hourOfDay, int minute) {
mHour = hourOfDay;
mMinute = minute;
}
};
now, to .setText for the textview that CALLED the timepicker after the TimePickerDialog.OnTimeSetListener callback, how should I write the code?
The answer is very simple but I lack OOP knowledge and still learning.
Thanks...
You need to use a global varible. say,String fromWhere="";
now,
textview1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
fromWhere="textview1";
showDialog(TIME_DIALOG_ID);
}
});
textview2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
fromWhere="textview2";
showDialog(TIME_DIALOG_ID);
}
});
...
private TimePickerDialog.OnTimeSetListener mTimeSetListener =
new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(android.widget.TimePicker view,
int hourOfDay, int minute) {
if(fromWhere.equals(textview1))
// set hour and minute to according variable and textview
else if(fromWhere.equals(textview2))
// set hour and minute to according variable and textview
.. //so on for others
//mHour = hourOfDay;
//mMinute = minute;
fromWhere="";
}
};
create a member variable (say int whichViewClicked = 0) in your class to keep track of the textview clicked to bring-up the time-picker.
Now if you click textview1 set whichViewClicked = 1, if textview2 is clicked set whichViewClicked = 2 and so on. In the onTimeSet() method check the value of whichViewClicked and set the textview text accordingly
Use EditText and we can get time pikker long press on edit text.
EditText timeDisplay=(EditText)findViewById(R.id.timeDisplay);
timeDisplay.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v) {
showDialog(TIME_DIALOG_ID);
}
});

Categories