I used this question to get the timepicker when clicking on editext.
Please note that I am putting the code in a fragment.
What i've changed is the following:
Added : Context ctx; to the settime.java
On the line:
SetTime fromTime = new SetTime(chostime,this);
It is telling me : the constructor SetTime(editText, AppointFragment) is not defined.
I’ve tried to change it into :
SetTime fromTime = new SetTime(chostime,getActivity());
When trying to run the application gice me the following error
12-30 18:03:55.120: E/AndroidRuntime(1376): java.lang.NullPointerException
Here is the code :
AppointFragment.java
package com.example.appointapp;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.DatePicker;
import android.widget.EditText;
public class AppointFragment extends Fragment{
private static final String TAG = "AppoinFragment";
EditText chosdate, chostime;
private Appointment mappointment;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mappointment= new Appointment();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState){
View v = inflater.inflate(R.layout.fragment_appoint, parent, false);
chosdate = (EditText)v.findViewById(R.id.datea_text);
chostime = (EditText)v.findViewById(R.id.timea_text);
SetTime fromTime = new SetTime(chostime,this);
chosdate.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
DialogFragment datePickerFragment = new DatePickerFragment() {
#Override
public void onDateSet(DatePicker view, int year, int month, int day) {
Log.d(TAG, "onDateSet");
Calendar c = Calendar.getInstance();
c.set(year, month, day);
String myFormat = "dd/MM/yy";
SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
chosdate.setText(sdf.format(c.getTime()));
chosdate.requestFocus();
}
};
datePickerFragment.show(getActivity().getSupportFragmentManager(), "datePicker");
}
}
});
return v;
}
}
SetTime.java
package com.example.appointapp;
import java.util.Calendar;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Context;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.widget.EditText;
import android.widget.TimePicker;
class SetTime implements OnFocusChangeListener, OnTimeSetListener {
private EditText editText;
private Calendar myCalendar;
Context ctx;
public SetTime(EditText editText, Context ctx){
this.editText = editText;
this.editText.setOnFocusChangeListener(this);
this.myCalendar = Calendar.getInstance();
}
#Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
int hour = myCalendar.get(Calendar.HOUR_OF_DAY);
int minute = myCalendar.get(Calendar.MINUTE);
new TimePickerDialog(ctx, this, hour, minute, true).show();
}
}
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
this.editText.setText( hourOfDay + ":" + minute);
}
}
First override onActivityCreated() in AppointFragment and then use the getActivity() to create SetTime object.
private SetTime fromTime;
private EditText chosdate, chostime;
...
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
fromTime = new SetTime(chostime,getActivity());
}
The complete code for setting the time using Fragments is below. You can use the same approach for setting the date too.
MainActivity.java
public class MainActivity extends AppCompatActivity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create a new Fragment to be placed in the activity layout
ChildFragment firstFragment = new ChildFragment();
// In case this activity was started with special instructions from an
// Intent, pass the Intent's extras to the fragment as arguments
//firstFragment.setArguments(getIntent().getExtras());
// Add the fragment to the 'fragment_container' FrameLayout
getSupportFragmentManager().beginTransaction()
.add(R.id.frameLayout, firstFragment).commit();
}
ChildFragment.java (For displaying EditTexts)
public class ChildFragment extends Fragment implements View.OnClickListener, TimePickerFragment.Callback
{
private EditText editText;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.child_fragment, null, false);
editText = (EditText) view.findViewById(R.id.time_edit_text);
editText.setOnClickListener(this);
return view;
}
#Override
public void onClick(View view)
{
if(view == editText)
{
TimePickerFragment dialog = new TimePickerFragment();
dialog.setTargetFragment(this, 1); //request code
dialog.show(getFragmentManager(),"dialog");
}
}
#Override
public void onTimeSelected(String time)
{
editText.setText(time);
}
}
TimePickerFragment.java
public class TimePickerFragment extends DialogFragment
implements TimePickerDialog.OnTimeSetListener {
public interface Callback
{
public void onTimeSelected(String time);
}
private Callback timeCallback;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current time as the default values for the picker
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
timeCallback = (Callback) getTargetFragment();
// Create a new instance of TimePickerDialog and return it
return new TimePickerDialog(getActivity(), this, hour, minute,
DateFormat.is24HourFormat(getActivity()));
}
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
// Do something with the time chosen by the user
timeCallback.onTimeSelected(hourOfDay + ":" + minute + ":00");
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/frameLayout"/>
</RelativeLayout>
child_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/time_edit_text"/>
</LinearLayout>
Here is the code :
AppointFragment.java
package com.example.appointapp;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.DatePicker;
import android.widget.EditText;
public class AppointFragment extends Fragment{
private static final String TAG = "AppoinFragment";
EditText chosdate, chostime;
private Appointment mappointment;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mappointment= new Appointment();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState){
View v = inflater.inflate(R.layout.fragment_appoint, parent, false);
chosdate = (EditText)v.findViewById(R.id.datea_text);
chostime = (EditText)v.findViewById(R.id.timea_text);
SetTime fromTime = new SetTime(chostime,this);
chosdate.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
DialogFragment datePickerFragment = new DatePickerFragment() {
#Override
public void onDateSet(DatePicker view, int year, int month, int day) {
Log.d(TAG, "onDateSet");
Calendar c = Calendar.getInstance();
c.set(year, month, day);
String myFormat = "dd/MM/yy";
SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
chosdate.setText(sdf.format(c.getTime()));
chosdate.requestFocus();
}
};
datePickerFragment.show(getActivity().getSupportFragmentManager(), "datePicker");
}
}
});
return v;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
SetTime fromTime = new SetTime(chostime,getActivity());
}
}
SetTime.java
package com.example.appointapp;
import java.util.Calendar;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Context;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.widget.EditText;
import android.widget.TimePicker;
class SetTime implements OnFocusChangeListener, OnTimeSetListener {
private EditText editText;
private Calendar myCalendar;
Context ctx;
public SetTime(EditText editText, Context ctx){
this.editText = editText;
this.editText.setOnFocusChangeListener(this);
this.myCalendar = Calendar.getInstance();
}
#Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
int hour = myCalendar.get(Calendar.HOUR_OF_DAY);
int minute = myCalendar.get(Calendar.MINUTE);
new TimePickerDialog(ctx, this, hour, minute, true).show();
}
}
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
this.editText.setText( hourOfDay + ":" + minute);
}
}
SingleFragmentAcitivity.java
public abstract class SingleFragmentActivity extends FragmentActivity {
protected abstract Fragment createFragment();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fragment);
FragmentManager fm = getSupportFragmentManager();
Fragment fragment = fm.findFragmentById(R.id.fragmentContainer);
if (fragment == null) {
fragment = createFragment();
fm.beginTransaction()
.add(R.id.fragmentContainer, fragment)
.commit();
}
}
}
Appointactivity.java
package com.example.appointapp;
import android.support.v4.app.Fragment;
public class AppointActivity extends SingleFragmentActivity {
#Override
protected Fragment createFragment() {
return new AppointFragment();
}
}
Fragment_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="#+id/new_patient"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/new_patient" />
<Button
android:id="#+id/new_appoint"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/new_appoint"/>
</LinearLayout>
Fragment_appoint.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Spinner
android:id="#+id/Patients_list"
android:layout_width="117dp"
android:layout_height="wrap_content" />
<EditText
android:id="#+id/datea_text"
android:layout_width="143dp"
android:layout_height="wrap_content"
android:hint="#string/datea_text_hint" />
<EditText
android:id="#+id/timea_text"
android:layout_width="141dp"
android:layout_height="wrap_content"
android:hint="#string/timea_text_hint" />
<Button
android:id="#+id/savea_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="#string/savea_button" />
</LinearLayout>
Thank you for ur help
i solved the issue using the following code in my fragment:
chostime.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Calendar mcurrentTime = Calendar.getInstance();
int hour = mcurrentTime.get(Calendar.HOUR_OF_DAY);
int minute = mcurrentTime.get(Calendar.MINUTE);
TimePickerDialog mTimePicker;
mTimePicker = new TimePickerDialog(getActivity(), new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
chostime.setText( selectedHour + ":" + selectedMinute);
}
}, hour, minute, true);//Yes 24 hour time
mTimePicker.setTitle("Select Time");
mTimePicker.show();
}
});
Thank you
Related
I tried to modify this time picker I found here on stackoverflow and placed it in a dialog in my application. When I try to pick the time the result is not what I setted but it is the time of the device, so the time isn't set well. The function TimeSetting is used to call the time picker. I tryed to make it start from zero and take the right time but with no result. Can someone help me find out where the error is?
here is the ExampleDialog.java file:
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatDialogFragment;
import com.ikovac.timepickerwithseconds.MyTimePickerDialog;
import com.ikovac.timepickerwithseconds.TimePicker;
import java.util.Calendar;
public class ExampleDialog extends AppCompatDialogFragment {
private EditText textInputNome;
private ExampleDialogListener listener;
private Button positiveButton;
private TextView text_view_timesec;
private Button SetTimeBTN;
private String nome = null;
private int timeInSeconds=-1;
private int hourOfDay;
private int minute;
private int seconds;
/*for MainActivity*/
public interface ExampleDialogListener {
boolean applyProgram(String nome);
}
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
final LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.layout_dialog, null);
textInputNome = view.findViewById(R.id.tiCrea);
SetTimeBTN=view.findViewById(R.id.btn_SetTime);
text_view_timesec=view.findViewById(R.id.textView3);
textInputNome.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
TimeSetting();
}
#SuppressLint("SetTextI18n")
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
nome =textInputNome.getText().toString().trim();
TimeSetting();
}
#Override
public void afterTextChanged(Editable s) {
TimeSetting();
}
});
builder.setView(view);
builder.setTitle("Nome programma");
builder.setNegativeButton("delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
builder.setPositiveButton("create", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
String nome = textInputNome.getText().toString().trim();
listener.applyProgram(nome);
}
});
Dialog dialog = builder.create();
return dialog;
}
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
try {
listener = (ExampleDialogListener) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString() +
"must implement ExampleDialogListener");
}
}
#Override
public void onDetach() {
super.onDetach();
listener = null;
}
#Override
public void onStart() {
super.onStart();
AlertDialog d = (AlertDialog) getDialog();
if (d != null ) {
positiveButton = d.getButton(Dialog.BUTTON_POSITIVE);
positiveButton.setEnabled(false);
}
}
private void TimeSetting(){
SetTimeBTN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getContext(), "Btn clicked", Toast.LENGTH_SHORT).show();
Calendar c = Calendar.getInstance();
MyTimePickerDialog mTimePicker = new MyTimePickerDialog(getContext(), new MyTimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute, int seconds) {
SetTimeBTN.setText(getString(R.string.time) + String.format("%02d", hourOfDay) + ":" + String.format("%02d", minute) + ":" + String.format("%02d", seconds));
}
}, hourOfDay=c.get(Calendar.HOUR_OF_DAY), minute=c.get(Calendar.MINUTE), seconds=c.get(Calendar.SECOND), true);
timeInSeconds = ((hourOfDay * 60 * 60) + (minute * 60) + seconds);
text_view_timesec.setText("hh=" + hourOfDay + " mm=" + minute + " ss=" + seconds + " time tot=" + timeInSeconds);
positiveButton.setEnabled(!nome.isEmpty() && timeInSeconds > 0);
mTimePicker.show();
}
});
}
}
Here is the xml of the dialog:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/time_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.google.android.material.textfield.TextInputEditText
android:id="#+id/tiCrea"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/name"
android:inputType="text" />
</com.google.android.material.textfield.TextInputLayout>
<Button
android:id="#+id/btn_SetTime"
style="#style/Widget.AppCompat.Button.Borderless"
android:layout_width="186dp"
android:layout_height="wrap_content"
android:text="#string/clickToSetTime"
android:textAlignment="viewStart"
android:gravity="start" />
<TextView
android:id="#+id/textView3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="here is the time setted from the timepkr" />
</LinearLayout>
in onCreate method change this two lines
final LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.layout_dialog, null);
to
final LinearLayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.layout_dialog, (ViewGroup)R.id.time_view");//here the id of the root LinearLayout in the XMl File layout_dialog.
I have googled alot. But i did't get the solution.
My issue is i have one fragment. In the fragment i am inflating some cards ie the swipe cards. for that swipe cards layout im using SwipeStackAdapter to inflate the view xml.
The in one of my xml view im trying to implement the datepicker.
TaskCardListShow.java fragment code
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.BaseAdapter;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.support.v7.app.AppCompatActivity;
import com.jmedeisis.draglinearlayout.DragLinearLayout;
import java.util.ArrayList;
import java.util.List;
import link.fls.swipestack.SwipeStack;
public class TaskCardListShow extends Fragment implements SwipeStack.SwipeStackListener, View.OnClickListener {
private ArrayList<String> mData;
private ArrayList<String> LayOutData;
private SwipeStack mSwipeStack;
private SwipeStackAdapter mAdapter;
public int cardCounter;
Context context;
AutoCompleteTextView autoTextView;
public TaskCardListShow() {
}
public static TaskCardListShow newInstance() {
TaskCardListShow _TaskCardListShow = new TaskCardListShow();
return _TaskCardListShow;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.task_card_list_show, container, false);
mSwipeStack = (SwipeStack) view.findViewById(R.id.swipeStack);
mData = new ArrayList<>();
LayOutData = new ArrayList<>();
mAdapter = new SwipeStackAdapter(mData,LayOutData);
mSwipeStack.setAdapter(mAdapter);
mSwipeStack.setListener(this);
context=getActivity().getApplicationContext();
cardCounter=7;// write function for getting card count.
fillStackCard();
return view;
}
private void fillStackCard() {
for (int x = 0; x <cardCounter; x++) {
mData.add(getString(R.string.dummy_text) + " " + (x + 1));
LayOutData.add(getString(R.string.str_card)+ (x + 1));
}
}
#Override
public void onClick(View v) {
}
#Override
public void onViewSwipedToRight(int position) {
String swipedElement = mAdapter.getItem(position);
}
#Override
public void onViewSwipedToLeft(int position) {
String swipedElement = mAdapter.getItem(position);
}
#Override
public void onStackEmpty() {
removeTaskCardFragment();
}
public void removeTaskCardFragment(){
FragmentManager manager = getActivity().getSupportFragmentManager();
FragmentTransaction mFragmentTransaction = manager.beginTransaction();
TaskCardListShow _TaskCardListShowFragment = new TaskCardListShow();
mFragmentTransaction.remove(_TaskCardListShowFragment);
mFragmentTransaction.commit();
manager.popBackStack();
}
public class SwipeStackAdapter extends BaseAdapter {
private List<String> mData;
private List<String> LayOutData;
DragLinearLayout dragDropAndroidLinearLayout;
public SwipeStackAdapter(List<String> data,List<String> Ldata) {
this.mData = data;
this.LayOutData = Ldata;
}
#Override
public int getCount() {
return mData.size();
}
#Override
public String getItem(int position) {
return mData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
String LName=LayOutData.get(position);
try {
int id = getActivity().getApplicationContext().getResources().
getIdentifier(LName, "layout", getActivity().getPackageName());
convertView = getActivity().getLayoutInflater().inflate(id, parent, false);
if(position==4){ // my date picker layout will come this postion.
}
} catch (Exception e) {
e.printStackTrace();
}
return convertView;
}
}
card_4.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_height="match_parent"
android:layout_width="match_parent"
card_view:cardCornerRadius="#dimen/card_corner_radius"
card_view:cardElevation="#dimen/elevation_large"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:gravity="center"
android:id="#+id/TxtQuestion">
<TextView
android:id="#+id/textViewCard"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:gravity="top"
android:textColor="#color/colorAccent"
android:textStyle="bold|italic"
android:textSize="20sp"
android:padding="30dp"
android:layout_gravity="top|center_horizontal|center_vertical"
android:text="Date picker template"/>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_below="#+id/TxtQuestion"
android:layout_centerInParent="true"
android:id="#+id/linearLayout">
<DatePicker
android:id="#+id/dpResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
</RelativeLayout>
</android.support.v7.widget.CardView>
Can you please guide me to do this. I have tried lots of method but it is not working i my case
I have solved my problem by,
in my adapter
final TextView _dpResult=(TextView)convertView.findViewById(R.id.dpResult);
_dpResult.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
DialogFragment newFragment = new SelectDateFragment( );
newFragment.show(getFragmentManager(), "DatePicker");
}
});
SelectDateFragment
public class SelectDateFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Calendar calendar = Calendar.getInstance();
int yy = calendar.get(Calendar.YEAR);
int mm = calendar.get(Calendar.MONTH);
int dd = calendar.get(Calendar.DAY_OF_MONTH);
return new DatePickerDialog(getActivity(), this, yy, mm, dd);
}
public void onDateSet(DatePicker view, int yy, int mm, int dd) {
populateSetDate(yy, mm+1, dd);
}
public void populateSetDate(int year, int month, int day) {
TextView dpResult= (TextView)getActivity().findViewById(R.id.dpResult);
dpResult.setText(year+"-"+month+"-"+day);
}
}
The xml coding for the date picker is
<TextView
android:id="#+id/dpResult"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:hint="yyyy-mm-dd" />
Now i am able see the date-picker on my card. Thanks
Fairly new to Android and I am trying to do some background color changes. Basically I have a main activity that only has a FrameLayout in it's xml. When the activity is created it opens up a fragment for my program. I have a menu item that when clicked pops a dialog box with 3 seekbars(red, green, blue). I want to change the background color to whatever the seekbars position is. I have all the code finished for the seekbars and I know it works on a simple app I created. For reasons to me unknown my app fails when i try to open the dialog box. What is the proper way to set this up in the Main Activity? I want the user to be able to change the background color whenever they want. All my fragment layouts are transparent. This is the tutorial I have been working off of. http://android-er.blogspot.com/2009/08/change-background-color-by-seekbar.html Any advice would be great. I think my problem is I do not fully understand how to access my main_activity's FrameLayout from with-in my MainActivity java class.
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical"
android:background="#e3a153">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/fragmentView"></FrameLayout>
</LinearLayout>
Color_seekbar_selecter.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/myScreen"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Change color"
/>
<SeekBar
android:id="#+id/mySeekingBar_R"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:max="255"
android:progress="0"/>
<SeekBar
android:id="#+id/mySeekingBar_G"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:max="255"
android:progress="0"/>
<SeekBar
android:id="#+id/mySeekingBar_B"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:max="255"
android:progress="0"/>
</LinearLayout>
menu_main.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".MainActivity">
<item android:id="#+id/menu_settings"
android:title="Green" />
<item android:id="#+id/menu_red"
android:title="Red" />
<item android:id="#+id/menu_blue"
android:title="Blue" />
<item android:id="#+id/menu_tan"
android:title="Tan" />
</menu>
MainActivity.java
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Color;
import android.os.Build;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.text.Layout;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.Toast;
import java.util.zip.Inflater;
public class MainActivity extends ActionBarActivity {
//public CategoryFragment categoryFragment;
//public RecipeFragment recipeFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(savedInstanceState == null)
{
CategoryFragment categoryFragment = new CategoryFragment();
getSupportFragmentManager().beginTransaction()
.add(R.id.fragmentView, categoryFragment, "categoryFrag")
.commit();
}
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
protected void onPostResume() {
super.onPostResume();
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate( R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId())
{
case R.id.menu_green:
}
return super.onOptionsItemSelected(item);
}
}
I have tried for hours to figure this out, but I just don't know where to put what.
This is the code from the example that I found in the link posted above.
import android.app.Activity;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.SeekBar;
public class SeekColorActivity extends Activity {
private int seekR, seekG, seekB;
SeekBar redSeekBar, greenSeekBar, blueSeekBar;
LinearLayout mScreen;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mScreen = (LinearLayout) findViewById(R.id.myScreen);
redSeekBar = (SeekBar) findViewById(R.id.mySeekingBar_R);
greenSeekBar = (SeekBar) findViewById(R.id.mySeekingBar_G);
blueSeekBar = (SeekBar) findViewById(R.id.mySeekingBar_B);
updateBackground();
redSeekBar.setOnSeekBarChangeListener(seekBarChangeListener);
greenSeekBar.setOnSeekBarChangeListener(seekBarChangeListener);
blueSeekBar.setOnSeekBarChangeListener(seekBarChangeListener);
}
private SeekBar.OnSeekBarChangeListener seekBarChangeListener
= new SeekBar.OnSeekBarChangeListener()
{
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
updateBackground();
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
};
private void updateBackground()
{
seekR = redSeekBar.getProgress();
seekG = greenSeekBar.getProgress();
seekB = blueSeekBar.getProgress();
mScreen.setBackgroundColor(
0xff000000
+ seekR * 0x10000
+ seekG * 0x100
+ seekB
);
}
}
categoryFragment.java
package com.example.mikesgamerig.finalproject;
import android.app.AlertDialog;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
public class CategoryFragment extends Fragment {
private ArrayList<String> categoryNameArrayList;
private ArrayAdapter<String> adapter;
private AlertDialog alertDialog;
private AlertDialog alertDialogDelete;
private EditText categoryEditText;
private String getCategoryName;
private List<Category> cats;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//create view
View rootView = inflater.inflate(R.layout.fragment_category, container, false);
//initialize all variables and widgets
inflater = getLayoutInflater(savedInstanceState);
alertDialog = new AlertDialog.Builder(getActivity()).create();
alertDialog.setView(inflater.inflate(R.layout.dialog_add_category, null));
alertDialogDelete = new AlertDialog.Builder(getActivity()).create();
alertDialogDelete.setView(inflater.inflate(R.layout.dialog_delete_category, null));
Button buttonAddCategory = (Button) rootView.findViewById(R.id.addCategoryButton);
ListView categoryListView = (ListView) rootView.findViewById(R.id.list);
//Array list to store names of categories
categoryNameArrayList = new ArrayList<String>();
//List of Category Objects
cats = Category.listAll(Category.class);
getCategoryNames();
//iterate through the CategoryList and attach to the ArrayList
//create adapter and fill the listView with all the name of categories
adapter = new ArrayAdapter<String>(getActivity(), R.layout.rowlayout, R.id.label, categoryNameArrayList);
categoryListView.setAdapter(adapter);
//set OnClick listener for the add category Button.
// This calls another method that will open a custom dialog box
buttonAddCategory.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
DisplayAddCategoryDialogBox();
}
});
//set an onItemLongClick listener for the ListView.
//First have to setLongClickable to true.
//the OnItemLongClick listener will call a method to open a custom Dialog to delete a category.
categoryListView.setLongClickable(true);
categoryListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
DeleteCategory(i);
return true;
}
});
//opens up a new fragment with a list of recipes for the specific category.
categoryListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String name = categoryNameArrayList.get(i);
RecipeFragment fragment = new RecipeFragment();
fragment.SetTitleName(name);
getFragmentManager().beginTransaction()
.setCustomAnimations(R.anim.slide_in_right, R.anim.slide_out_left, R.anim.slide_in_left, R.anim.slide_out_right)
.replace(R.id.fragmentView, fragment)
.addToBackStack(null).commit();
}
});
return rootView;
}
//This method will Display a custom add category Dialog Box.
public void DisplayAddCategoryDialogBox(){
//Show the Dialog box to enter a new category name.
alertDialog.show();
categoryEditText = (EditText) alertDialog.findViewById(R.id.categoryEditText);
Button saveCategoryDialogBtn = (Button) alertDialog.findViewById(R.id.saveBtn);
Button cancelDialogButton = (Button) alertDialog.findViewById(R.id.cancelBtn);
saveCategoryDialogBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
getCategoryName = categoryEditText.getText().toString();
//Log.d("STRING VALUE:", getCategoryName);
Category test = new Category(getCategoryName);
test.save();
categoryNameArrayList.add(test.getName());
//Log.d("added Value: ", test.getName());
adapter.notifyDataSetChanged();
alertDialog.hide();
}
});
cancelDialogButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
alertDialog.hide();
}
});
}
//this method will display a custom Delete Category Alert Dialog box.
public void DeleteCategory(final int i)
{
alertDialogDelete.show();
Button noBtn = (Button) alertDialogDelete.findViewById(R.id.noBtn);
noBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
alertDialogDelete.hide();
}
});
Button yesBtn = (Button) alertDialogDelete.findViewById(R.id.yesBtn);
yesBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String tempString = categoryNameArrayList.get(i);
//Log.d("VALUE OF STRING= ", tempString);
categoryNameArrayList.remove(i);
for (Category category : cats) {
String name = category.getName();
if (name.equals(tempString)) {
category.delete();
}
}
adapter.notifyDataSetChanged();
alertDialogDelete.hide();
}
});
}
//Filles the Array
public void getCategoryNames()
{
for(Category category : cats)
{
String name = category.getName();
categoryNameArrayList.add(name);
}
}
}
I want to create a TimePickerDialog using FragmentDialog and exchange data between my fragment and the TimePickerDialog . I already created a DatePickerDialog but I don't know how to create a TimePickerDialog . I want that when the user click the button in my fragment TimePickerDialog appear .
This is how I create The DatePickerDialog :
import java.util.Calendar; import java.util.Date; import
java.util.GregorianCalendar;
import android.app.Activity; import android.app.AlertDialog; import
android.app.Dialog; import android.content.DialogInterface; import
android.content.Intent; import android.os.Bundle; import
android.support.v4.app.DialogFragment; import android.view.View;
import android.widget.DatePicker; import
android.widget.DatePicker.OnDateChangedListener;
public class DatePickerFragment extends DialogFragment {
public static final String EXTRA_DATE = "criminalintent.DATE";
Date mDate;
public static DatePickerFragment newInstance(Date date) {
Bundle args = new Bundle();
args.putSerializable(EXTRA_DATE, date);
DatePickerFragment fragment = new DatePickerFragment();
fragment.setArguments(args);
return fragment;
}
private void sendResult(int resultCode) {
if (getTargetFragment() == null)
return;
Intent i = new Intent();
i.putExtra(EXTRA_DATE, mDate);
getTargetFragment()
.onActivityResult(getTargetRequestCode(), resultCode, i);
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
mDate = (Date)getArguments().getSerializable(EXTRA_DATE);
Calendar calendar = Calendar.getInstance();
calendar.setTime(mDate);
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
View v = getActivity().getLayoutInflater()
.inflate(R.layout.dialog_date, null);
DatePicker datePicker = (DatePicker)v.findViewById(R.id.dialog_date_datePicker);
datePicker.init(year, month, day, new OnDateChangedListener() {
public void onDateChanged(DatePicker view, int year, int month, int day) {
mDate = new GregorianCalendar(year, month, day).getTime();
// update argument to preserve selected value on rotation
getArguments().putSerializable(EXTRA_DATE, mDate);
}
});
return new AlertDialog.Builder(getActivity())
.setView(v)
.setTitle(R.string.date_picker_title)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
sendResult(Activity.RESULT_OK);
}
})
.create();
} }
CrimeFragment
import java.util.Date; import java.util.UUID;
import android.app.Activity; import android.content.Intent; import
android.os.Bundle; import android.support.v4.app.Fragment; import
android.support.v4.app.FragmentManager; import android.text.Editable;
import android.text.TextWatcher; import android.view.LayoutInflater;
import android.view.View; import android.view.ViewGroup; import
android.webkit.WebView.FindListener; import android.widget.Button;
import android.widget.CheckBox; import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener; import
android.widget.EditText;
public class CrimeFragment extends Fragment {
public static final String EXTRA_CRIME_ID = "criminalintent.CRIME_ID";
private static final String DIALOG_DATE = "date";
private static final int REQUEST_DATE = 0;
Crime mCrime;
EditText mTitleField;
Button mDateButton;
CheckBox mSolvedCheckBox;
Button mTime;
String time;
public static CrimeFragment newInstance(UUID crimeId) {
Bundle args = new Bundle();
args.putSerializable(EXTRA_CRIME_ID, crimeId);
CrimeFragment fragment = new CrimeFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
UUID crimeId = (UUID)getArguments().getSerializable(EXTRA_CRIME_ID);
mCrime = CrimeLab.get(getActivity()).getCrime(crimeId);
}
public void updateDate() {
mDateButton.setText(mCrime.getDate().toString());
}
public void updateTime() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_crime, parent, false);
mTitleField = (EditText)v.findViewById(R.id.crime_title);
mTitleField.setText(mCrime.getTitle());
mTitleField.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence c, int start, int before, int count) {
mCrime.setTitle(c.toString());
}
public void beforeTextChanged(CharSequence c, int start, int count, int after) {
// this space intentionally left blank
}
public void afterTextChanged(Editable c) {
// this one too
}
});
mDateButton = (Button)v.findViewById(R.id.crime_date);
updateDate();
mDateButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
FragmentManager fm = getActivity()
.getSupportFragmentManager();
DatePickerFragment dialog = DatePickerFragment
.newInstance(mCrime.getDate());
dialog.setTargetFragment(CrimeFragment.this, REQUEST_DATE);
dialog.show(fm, DIALOG_DATE);
}
});
mTime = (Button) v.findViewById(R.id.crime_time);
mSolvedCheckBox = (CheckBox)v.findViewById(R.id.crime_solved);
mSolvedCheckBox.setChecked(mCrime.isSolved());
mSolvedCheckBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// set the crime's solved property
mCrime.setSolved(isChecked);
}
});
return v;
}
#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();
}
} }
Now I want to create a TimePickerDialog .
public class DialogFragmentTimePicker extends DialogFragment implements OnTimeSetListener {
public static final String ARG_HOUR = "hour";
public static final String ARG_MINUTE = "minute";
private OnTimeSetListener mListener;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current time as the default values for the picker
int hour, minute;
if (getArguments() != null) {
hour = getArguments().getInt(ARG_HOUR);
minute = getArguments().getInt(ARG_MINUTE);
} else {
final Calendar c = Calendar.getInstance();
hour = c.get(Calendar.HOUR_OF_DAY);
minute = c.get(Calendar.MINUTE);
}
// Create a new instance of TimePickerDialog and return it
return new TimePickerDialog(getActivity(), this, hour, minute, DateFormat.is24HourFormat(getActivity()));
}
public void setOnTimeSetListener(OnTimeSetListener listener) {
mListener = listener;
}
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
if (mListener != null) {
mListener.onTimeSet(view, hourOfDay, minute);
}
}
}
How do I make this time picker set the edittext box with the time that the TimePickerDialog set?
package com.example.d;
import java.util.Calendar;
import android.os.Bundle;
import android.app.Activity;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.view.View;
import android.widget.EditText;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
int hour,min;
//static final int TIME_DIALOG_ID=0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText etOne = (EditText) findViewById(R.id.editText1);
etOne.setOnClickListener(new EditText.OnClickListener() {
public void onClick(View v) {
//Do stuff here
Calendar c=Calendar.getInstance();
int hour=c.get(Calendar.HOUR);
int min=c.get(Calendar.MINUTE);
showTimeDialog(v, hour, min);
}
});
}
OnTimeSetListener timeSetListener;
public void showTimeDialog(View v, int hour, int min)
{
(new TimePickerDialog(this, timeSetListener, hour, min, true)).show();
//how do I make this time picker set the edittext box with the time that the TimePickerDialog set
}
}
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/relativeLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:width="320px">
<requestFocus />
</EditText>
</RelativeLayout>
public class MainActivity extends Activity {
int hour = -1, min = -1;
static final int TIME_DIALOG_ID = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText etOne = (EditText) findViewById(R.id.editText1);
etOne.setOnClickListener(new EditText.OnClickListener() {
public void onClick(View v) {
// Do stuff here
if (hour == -1 || min == -1) {
Calendar c = Calendar.getInstance();
hour = c.get(Calendar.HOUR);
min = c.get(Calendar.MINUTE);
}
showTimeDialog(v, hour, min);
}
});
}
public void showTimeDialog(View v, int hour, int min) {
(new TimePickerDialog(MainActivity.this, timeSetListener, hour, min,
true)).show();
}
public TimePickerDialog.OnTimeSetListener timeSetListener = new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
hour = hourOfDay;
min = minute;
EditText et = (EditText) findViewById(R.id.editText1);
et.setText(hour + " : " + min);
}
};
}
You can do it in onTimeSetListener like this
private TimePickerDialog.OnTimeSetListener mTimeSetListener = new TimePickerDialog.OnTimeSetListener()
{
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute)
{
setTimeEditText.setText(hour + ":" + minute);
}
};
You have to creat an instance of OnTimeSetListener and in it's onTimeSet method you have the selected hour and minute.