I have a TimePickerDialog preference with a "TimePreference" class which extends DialogPreference:
public class TimePreference extends DialogPreference{
...
private TimePicker picker=null;
...
public TimePreference(Context ctxt, AttributeSet attrs){
super(ctxt, attrs);
setPositiveButtonText(android.R.string.ok);
setNegativeButtonText(android.R.string.cancel);
}
#Override
protected View onCreateDialogView(){
picker=new TimePicker(getContext());
return(picker);
}
...
}
I would like to add a third button, which will set the preference to the current time and close the dialog, like this:
The question is, is there some way of doing this using TimePickers or should I make a custom AlertDialog?
Thanks for your answers! I will show you how I finally managed it, just in case someone wants to do the same.
First, I have a layout file good_timedialog.xml which looks like I wanted:
Then I have a TimePreference class:
public class TimePreference extends DialogPreference{
private final static String lTag="CustomTimeDialog";
private TimePicker picker;
protected TimeObj lastTime;
public TimePreference(Context ctxt,AttributeSet atrs) {
super(ctxt,atrs);
setDialogLayoutResource(R.layout.good_timedialog); // this loads the layout
setPositiveButtonText("");
setNegativeButtonText(""); // hide default buttons
setDialogTitle(ctxt.getString(R.string.selectTimeTimePrefTitle));
}
#Override
protected void onBindDialogView(View v){
super.onBindDialogView(v);
v.findViewById(R.id.butCancel).setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v){
Log.d(lTag,"cancel clicked");
getDialog().dismiss();
}
});
v.findViewById(R.id.butNow).setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v){
Log.d(lTag,"now clicked");
saveToSP(true);
getDialog().dismiss();
}
});
v.findViewById(R.id.butOK).setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v){
Log.d(lTag,"ok clicked");
saveToSP(false);
getDialog().dismiss();
}
});
picker = (TimePicker) v.findViewById(R.id.timePicker);
if (picker!=null) {
picker.setCurrentHour(lastTime.hr);
picker.setCurrentMinute(lastTime.min);
} else { // if it is null
Log.w(lTag,"var picker is null!");
}
}
void saveToSP(boolean now){
if (now) lastTime = new TimeObj(); // make it the current time
else {
lastTime.hr = picker.getCurrentHour();
lastTime.min = picker.getCurrentMinute();
}
setSummary(lastTime.giveString()); // update Summary like hh:mm 16:28
int time = lastTime.giveMinutes(); // 10:30am will be 630 minutes
// save to sharedprefs
if(callChangeListener(time)){
persistInt(time);
if(getEditor().commit()) Log.d(lTag,"Successfully saved changes");
else Log.w(lTag,"Did NOT save changes");
}
}
//... more ...
}
And at the perferences.xml file, I can use <com.example.TimePreference android:key="test"/>
Dialog supports three buttons by default - positive, negative and cancel. You could rename them as per your wish and handle them accordingly.
Related
Long press
When I long-click on an item of the message, the item will display and the layout changes like the picture. I want to make this , but i don't have a keyword to find this solution. I need a keyword or some example to make it.
Many ways you can do. I am going to share one example.
Implement View.OnLongClickListener as follows
private void setupLongPress() {
imageButton.setOnLongClickListener(new View.OnLongClickListener(){
#Override
public boolean onLongClick(View v){
// here your staff
// we added dialog method here as follows
createPreviewDialog();
return false;
}
});
}
Now use LayoutInflater to inflate new layout as a popup windows
private Dialog createPreviewDialog() {
View view = LayoutInflater.from(getContext()).inflate(R.layout.dialog_preview, null);
LinearLayout closeButton = view.findViewById(R.id.close);
closeButton.setOnClickListener (new View.OnClickListener (){
#Override
public void onClick ( View view ) {
dismiss();
}
});
View okButton = view.findViewById(R.id.ok);
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dismiss();
// here your staff
}
});
builder.setView(view);
return builder.create();
}
I am trying to add specific behaviour to Button's onClick, so when they are clicked they have the custom behaviour on top of the specific action for each button.
I have recently started developing for Android and have little experience on the inner quirks of events and UI classes.
WHat I tried, the buttom performs the custom behaviour I write in the extended class, but then doesn't perform the onClick action I assigned to the button specifically.
This is the custom Button I'm trying to do.
public class CooldownButton extends Button implements View.OnClickListener
{
Timer cooldown;
public CooldownButton(Context context, AttributeSet attrs, int defStyle)
{
super(context, attrs, defStyle);
}
public CooldownButton(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CooldownButton(Context context)
{
super(context);
}
#Override
public void onClick(View v)
{
cooldown= new Timer();
cooldown.schedule(cooldownRun(),0,500);
setEnabled(false);
//performClick();
}
private TimerTask cooldownRun()
{
return new TimerTask()
{
#Override
public void run()
{
cooldown.cancel();
cooldown.purge();
setEnabled(true);
}
};
}
}
Then I use it on xml layouts like this:
<CooldownButton android:id="#+id/btnNext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onBtnNextClick" />
OnBtnNextClick is never called.
public void onBtnNextClick(View v)
{
if(v.getId() == R.id.btnNext)
{
//Do something
}
}
From what I am seeing you are disabling the button setEnabled(false); and then you want to perform some action on a next click onBtnNextClick(View v). You cannot click a button a second time if it has been disabled when it was first clicked.
I found a solution after following one of the comments indications.
It is not exactly the way I wanted to solve the issue but it gets close.
I scrapped the idea of making the click behaviour in a java class.
Instead I write a click listener in the MainActivity and then set the listener to all buttons I want to have this special click behaviour.
Button nextButton = (Button) layout.findViewById(R.id.btnNext);
nextButton.setOnClickListener(buttonClickListener);
The listener is as follows:
public View.OnClickListener buttonClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
final Button btn = (Button) v;
btn.setEnabled(false);
new Thread(new Runnable() {
#Override
public void run() {
try {Thread.sleep(1000); }
catch (InterruptedException e) {e.printStackTrace();}
MainActivity.this.runOnUiThread(new Runnable()
{
#Override
public void run(){ btn.setEnabled(true); }
});
}
}).start();
switch (v.getId()) {
case R.id.btnNext:
doSomething();
break;
//case R.id.foobar:
//break;
}
}
};
I want to increase the value of the text on the click of abutton. However, I want to increase the value by certain amount. My initial value is 250 and I want to increase the textvalue by 250 every time i click on button.
I have written logic for it but the value increases by one.
This is the relevant code:
public class SelectCartListViewAdapter extends BaseAdapter{
private Context mcontext;
private static int counter = 250;
private String stringVal;
public SelectCartListViewAdapter(Context c){
mcontext = c;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//... some other code
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.d("src", "Increasing value...");
counter++;
stringVal = Integer.toString(counter);
tv1.setText(stringVal);
}
});
//...some other code
return myView;
}
}
That's because you have used a incremental operator here,
counter++;
Incremental operator will increase value by one only.
It should be something like this,
counter= counter+actualValue;
Try this
int counter=0, staticCounter=250;
#Override
public void onClick(View v) {
counter= counter+staticCounter;
tv1.setText(String.valueOf(counter));
}
Replace part of your code with the below code fragment.
ImageButton button = (ImageButton)myView.findViewById(R.id.addbutton);
button.setOnClickListener(new OnClickListener() {
//private int _counter;
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//Toast.makeText(mcontext,"Button is clicked",Toast.LENGTH_SHORT).show();
Log.d("src", "Increasing value...");
counter+=250;
stringVal = Integer.toString(counter);
tv1.setText(stringVal);
// int value = (Integer.parseInt((String) tv1.getText()))+250;
// tv1.setText(value);
}
});
How to set null validation in edittextpreference dialog so that if it is null, the user should not be able to click ok and some message should be displayed in the dialog itself. I have been trying to find it for a long time but no success....
edttxtpref = (EditTextPreference) getPreferenceScreen().findPreference(
"edttxtkey");
edttxtpref.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(
android.preference.Preference preference, Object newValue) {
if (newValue.toString().trim().equals("")) {
Toast.makeText(getActivity(), "Username can not be empty",
Toast.LENGTH_LONG).show();
return false;
}
return true;
}
});
This way the validation is done and if we want to display the message in dialog itself then a custom dialog has to be created as already told by Phil.
I think what you are looking for is this. You are using the predefined PreferenceDialog (with EditText) and want to check if the Text is null. According to my knowledge, the "text" in this case is the changedPreference, therefore you can go with this:
Simply use an onPreferenceChangedListener for that.
yourPreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object changedValue) {
if(changedValue == null) {
// handle it being null
return false;
} else {
return true;
}
}
});
For more advanced requirements, I would recommend that you implement your own Dialog and inside it, do whatever you desire. You can make that happen by defining a Preference list entry in .xml and then spawn the Dialog upon clicking on it.
Preference yourCustomPref = (Preference) findPreference("yourPref");
yourCustomPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
// spawn your dialog here
return true;
}
});
This is how you could implement your custom EditText Dialog:
public Builder buildDialog(final Context c) {
AlertDialog.Builder builder = new AlertDialog.Builder(c);
builder.setTitle("EditText Dialog");
builder.setMessage("Enter text:");
LinearLayout llV = new LinearLayout(c);
llV.setOrientation(1); // 1 = vertical
final EditText patName = new EditText(c);
patName.setHint("Enter text...");
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, 1f);
lp.bottomMargin = 20;
lp.rightMargin = 30;
lp.leftMargin = 15;
patName.setLayoutParams(lp);
llV.addView(patName);
builder.setView(llV);
builder.setPositiveButton("Save", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if(patName.getText().toString().length() > 0) {
} else {
}
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
return builder;
}
And then call it like this:
buildDialog(yourcontext).show();
When edittext is null then ok button will be disabled and as soon as the text is entered it will be enabled::
public class CustomEditTextPreference extends EditTextPreference implements
OnClickListener {
public CustomEditTextPreference(Context ctx, AttributeSet attrs, int defStyle)
{
super(ctx, attrs, defStyle);
}
public CustomEditTextPreference(Context ctx, AttributeSet attrs)
{
super(ctx, attrs);
}
private class EditTextWatcher implements TextWatcher
{
#Override
public void onTextChanged(CharSequence s, int start, int before, int count){}
#Override
public void beforeTextChanged(CharSequence s, int start, int before, int count){}
#Override
public void afterTextChanged(Editable s)
{
onEditTextChanged();
}
}
EditTextWatcher m_watcher = new EditTextWatcher();
/**
* Return true in order to enable positive button or false to disable it.
*/
protected boolean onCheckValue(String value)
{
if (value.trim().equals(""))
{
return false;
}
return true;
}
protected void onEditTextChanged()
{
boolean enable = onCheckValue(getEditText().getText().toString());
Dialog dlg = getDialog();
if(dlg instanceof AlertDialog)
{
AlertDialog alertDlg = (AlertDialog)dlg;
Button btn = alertDlg.getButton(AlertDialog.BUTTON_POSITIVE);
btn.setEnabled(enable);
}
}
#Override
protected void showDialog(Bundle state)
{
super.showDialog(state);
getEditText().removeTextChangedListener(m_watcher);
getEditText().addTextChangedListener(m_watcher);
onEditTextChanged();
}
}
I'm new to android development..
I have this code in my main class:
Button prevBtn, pauseBtn, nextBtn;
EditText counterTxt;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_affirmations);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
prevBtn = (Button)findViewById(R.id.prevBtn);
pauseBtn = (Button)findViewById(R.id.pauseBtn);
nextBtn = (Button)findViewById(R.id.nextBtn);
counterTxt = (EditText)findViewById(R.id.counterTxt);
prevBtn.setOnClickListener(new View.OnClickListener() {
int t = Integer.parseInt(counterTxt.getText().toString());
public void onClick(View v) {
counterTxt.setText(String.valueOf(t-1));
}
});
nextBtn.setOnClickListener(new View.OnClickListener() {
int t = Integer.parseInt(counterTxt.getText().toString());
public void onClick(View v) {
counterTxt.setText(String.valueOf(t+1));
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_affirmations, menu);
return true;
}
When I click "Previous", the text field value becomes 19.
When I click "Next", the text field value becomes 21.
But it only displays these two values, nothing else, no matter if i click again. I want to subtract or add 1 whenever i click the appropriate buttons.
I think this happens because the event Listeners are inside onCreate() method? Any idea on how to make it update each time I click?
You need to move your parseInt inside your onClick:
nextBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
int t = Integer.parseInt(counterTxt.getText().toString());
counterTxt.setText(String.valueOf(t+1));
}
});
In both cases, t is defined as a member variable of the listener, and never changed. move it inside the onClick method instead, like this (in both cases):
public void onClick(View v) {
int t = Integer.parseInt(counterTxt.getText().toString());
counterTxt.setText(String.valueOf(t-1));
}