I have 5 buttons in my activity inside a linear layout.
I have written a code to display a toast message when I click one of those buttons.
It is displaying the toast message after 6 seconds of Click action.
I couldn't think what the problem could be..
Here is the code I have written in android studio
public class HomePage extends AppCompatActivity implements View.OnClickListener {
private Button loginButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_page);
makeNotificationBarTransparent();
loginButton = (Button)findViewById(R.id.login_btn);
loginButton.setOnClickListener(this);
Intent i = getIntent();
Toast.makeText(getApplicationContext(),i.getStringExtra("UserName"),Toast.LENGTH_LONG).show();
}
private void makeNotificationBarTransparent() {
//Making notification bar transparent
if(Build.VERSION.SDK_INT >= 21){
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(Color.TRANSPARENT);
}
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.login_btn:
Toast.makeText(getApplicationContext(),"CLicked",Toast.LENGTH_LONG).show();
break;
}
}
}
Can anyone tell me What could be the problem?
It might be the fact that you show another toast message that you set to show up, as two toast messages cannot display at once.
I am referring to this toast message:
Toast.makeText(getApplicationContext(),i.getStringExtra("UserName"),Toast.LENGTH_LONG).show();
You mean the Toast message will be show after clicking the button for 6 seconds?
Try to use this:
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
// show toast here...
}
}, 6000); // 6 seconds
Or you can use CountDownTimer:
new CountDownTimer(6000, 1000) {
public void onTick(long millisUntilFinished) {
// do every 1 second
}
public void onFinish() {
// show your toast after 6 seconds.
}
}.start();
Is this what you need? If not, tell me more about your problems :)
Related
I have a custom dialog box that I am displaying in the following way:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.dict_add_word_dialog_box);
ok = findViewById(R.id.dictDialog_confirmButton);
cancel = (Button) findViewById(R.id.dictDialog_cancelButton);
ok.setOnClickListener(this);
cancel.setOnClickListener(this);
}
This displays when tapping the Floating Action Button, via:
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
DictCustomDialogBoxClass customDialog = new DictCustomDialogBoxClass(DictionaryActivity.this);
customDialog.show();
refreshRecyclerView();
}
});
I'd like the refreshRecyclerView(); to run only once the user has pressed the OK button on the dialog box. How would I go about doing this?
In addition, how would I go about running it only if the user has pressed OK, and not Cancel?
Create a runnable with your refreshRecyclerView method in it:
Runnable r = new Runnable() {
#Override
public void run() {
refreshRecyclerView();
}
}
then create a handler for that runnable:
Handler handler = new Handler();
inside your onClickListener for the ok button trigger the runnable by calling the following:
handler.post(r);
Why not add a listener to your custom dialog?
var listener: Listener
public interface Listener {
void onPositiveActionPressed();
}
Then in your custom dialog's ok.onClickListener you'd have the below;
if(listener != null) {
listener.onPositiveActionPressed();
}
Finally;
DictCustomDialogBoxClass customDialog = new DictCustomDialogBoxClass(DictionaryActivity.this)
customDialog.listener = self
Of course having implemented DictCustomDialogBoxClass.Listener
I have started with android programming and I am trying to do:
Let the user enter their login credential.
If the user login credential is valid let them login.
If login credential is invalid then give them an error message saying that the user name or password entered is invalid.
For the last part, the problem is that I have a TextView with default hidden visibility. I want to make it visible for a few seconds and make it disappear.
This post and this post have helped but they are essentially trying to do the opposite.
My code is given below:
submitButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Check the validity of the user name.
if (valid) {
// Let the user log in.
} else {
// Make TextView visible for a few seconds.
}
}
});
How do I go about this?
In your case first you need to show TextView then make it INVISIBLE .
Use textView.postDelayed method as:
if(valid){ //let the user login }
else
{
// make TextView visible here
textView.setVisibility(View.VISIBLE);
//use postDelayed to hide TextView
textView.postDelayed(new Runnable() {
public void run() {
textView.setVisibility(View.INVISIBLE);
}
}, 3000);
//how to make the textview visible for a few seconds
}
To show any information or error message you can use small pop-up message for some time. Following the code and image for toast.
//display in short period of time
Toast.makeText(getApplicationContext(), "msg msg", Toast.LENGTH_SHORT).show();
You can use toast.
Context context = getApplicationContext();
CharSequence text = "Hello toast!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
Toasts in android
try this
mButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mTextView.setVisibility(View.VISIBLE);
v.postDelayed(new Runnable() {
#Override
public void run() {
mTextView.setVisibility(View.GONE);
}
}, 2000);
}
});
you can achieve this with the help of timertask,as your textview is invisible first make it visible and then with the help of timertask make it invisible again
submitButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//check the validity of the user name
if(valid)
{
//let the user login
}
else
{
txt.setVisibility(View.VISIBLE);
Timer t = new Timer(false);
t.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
public void run() {
txt.setVisibility(View.INVISIBLE);
}
});
}
}, 5000);
}
});
but i would suggest if you want user confirmation show error in alertdialog or a toast to show error would be fine
You can do this by using handler.
submitButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//check the validity of the user name
if(valid)
{
//let the user login
}
else
{
//how to make the textview visible for a few seconds
new Handler().postDelayed(new Runnable()
{
#Override
public void run()
{
mTextView.setVisibility(View.VISIBLE);
}
}, 1000/* 1sec delay */);
}
});
I have an ImageButton in my application.
<ImageButton
android:id="#+id/imageButton1"
android:layout_width="80dp"
android:layout_height="80dp"
android:clickable="true"
android:src="#drawable/button" />
I bind it to an onClickListener:
View.OnClickListener imgButtonHandler = new View.OnClickListener() {
public void onClick(View v) {
// Here I update the image source to a different image.
}
};
Now what happens is: when I click the imagebutton, the imagebutton changes to a
different image. But I want it to change back automatically after 0.5 sec (during the
same time the user should not be able to click anything). How do I
implement that? I tried to sleep in the onClick function in the listener, but it's
not working...
New edit:
The proposed answer will solve my problem if I only have one imagebutton. I tried it out
and both work like charm!
Actually it is not working as expected. During that 500ms, the user still could click!
It is not solving the problem...
Posting a delayed runnable might do the job.
public void onClick(View v) {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// change the background of the image button
(ImageButton)v.setBackgroundResource(R.drawable.someimage);
}
}, 500);
}
EDIT:
In fact, I've ran the following code on an actual device with two ImageButton and it works fine.
BTW, if you want the buttons to be un-clickable during the 500ms, just set it as imgBtn1.setClickable(false); and set it back to be clickable in the runnable as imgBtn1.setClickable(true);
public class TestFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.test_layout, container, false);
final ImageButton imgBtn1 = (ImageButton) view.findViewById(R.id.test_img_btn1);
final ImageButton imgBtn2 = (ImageButton) view.findViewById(R.id.test_img_btn2);
imgBtn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
imgBtn1.setBackgroundResource(R.drawable.device_type_apple);
imgBtn1.setClickable(false);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// change the background of the image button
imgBtn1.setBackgroundResource(R.drawable.device_type_windows);
imgBtn1.setClickable(true);
}
}, 500);
}
});
imgBtn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
imgBtn2.setBackgroundResource(R.drawable.device_type_apple);
imgBtn2.setClickable(false);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// change the background of the image button
imgBtn2.setBackgroundResource(R.drawable.device_type_android);
imgBtn2.setClickable(true);
}
}, 500);
}
});
return view;
}
}
You can use handle with runnable to auto update image
Handler mHandler = new Handler();
Runnable mUpdateTimer = new Runnable() {
#Override
public void run() {
// code update image here
// auto update after 0.5s
mHandler.postDelayed(mUpdateTimer, 500);
}
};
And when image button clicked:
View.OnClickListener imgButtonHandler = new View.OnClickListener() {
public void onClick(View v) {
mHandler.postDelayed(mUpdateTimer, 500);
}
};
Handler.postDelayed
this method is not good way ,see http://developer.android.com/reference/android/os/Handler.html#postDelayed(java.lang.Runnable,long)
it say
Returns true if the Runnable was successfully placed in to the message queue. Returns false on failure, usually because the looper processing the message queue is exiting. Note that a result of true does not mean the Runnable will be processed -- if the looper is quit before the delivery time of the message occurs then the message will be dropped.
so this methed may never invoke,it may be make you image button status never come back ,so you must be care the return value or use other widget ViewFliper,it can set animation when image switch and you can set delpoy .
I want to show another alert message(alert box/alert dialog) after the progress bar reaches 100%. How do I do that?
And Also is there any way to style that box (or both of them)?
Below is my code for an ProgressBar:
public class MainActivity extends Activity {
Button progress_button;
ProgressDialog pro_dialog;
Handler pro_handler;
int progress;
private static final int MAX_PROGRESS = 100;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
// intiliazing the buttons
progress_button = (Button) findViewById(R.id.button1);
progress_button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Creating progress dialog interface setting
// title,progressstyle,max_progress
pro_dialog = new ProgressDialog(MainActivity.this);
pro_dialog.setTitle("Making everything OK is in progress! Please be patient.");
pro_dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pro_dialog.setMax(MAX_PROGRESS);
progress = 0;
pro_dialog.show();
pro_dialog.setProgress(0);
pro_handler.sendEmptyMessage(0);
}
});
// set onclick listener for buttons
pro_handler = new Handler() {
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (progress >= MAX_PROGRESS) {
pro_dialog.dismiss();
} else {
progress++;
pro_dialog.incrementProgressBy(2);
pro_handler.sendEmptyMessageDelayed(0, 100);
}
}
};
}
First of all, it would make more sense if you could replace:
pro_dialog.incrementProgressBy(2);
with this:
pro_dialog.setProgress(progress);
Current code dismisses dialog after progress variable reaches MAX_PROGRESS, but current value of this variable isn't presented by the progress dialog.
If you would like to show AlertDialog, you can do it for example after "pro_dialog.dismiss()".
Case of Progress Dialog styling has been discused here.
I have a requirement of having a activity as dialog (Not an Alert dialog, instead a progress dialog). There are no ui components in this activity since this activity does server interaction, based on server response next activities are started. Only a progress dialog with cancel button needs to be shown in this activity. Now the problem is when ever this activity is launched just before progress dialog is displayed a small black rectanagle is visible for a second or more, also when this activity is finished this is visible. How to get rid of this ? or is there any better way of haveing a progress dialog as activity ?
-Thanks & regards,
Manju
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActivityAsDialogActivity.this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
String str ="Hellow World";
txtView = (TextView)findViewById(R.id.txtview);
this.setFinishOnTouchOutside(false);
txtView.setText(R.string.select_dialog);
ActivityAsDialogActivity.this.setTitle(R.string.app_name);
mProgressHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (mProgress >= MAX_PROGRESS) {
mProgressDialog.dismiss();
Intent intent = new Intent(ActivityAsDialogActivity.this, ActivityOne.class);
startActivity(intent);
finish();
} else {
mProgress++;
mProgressDialog.incrementProgressBy(1);
mProgressHandler.sendEmptyMessageDelayed(0, 100);
}
}
};//end of handler
showDialog(DIALOG_PROGRESS);
mProgressDialog.setProgress(0);
mProgressHandler.sendEmptyMessage(0);
}//end of onCreate()
#Override
public void onBackPressed(){
Log.d("Manju ==>"," back key pressed");
finish();
}
#Override
public void finish(){
Log.d("Manju ==>", " inside finish()");
super.finish();
}
In Creating Global Dialog, I used a transparent activity with a dialog inside. I think you can do the same thing. I do not recall facing the problem you are facing, and it worked perfectly.
Check it out