Android : Start Activity after button animation - java

I used an android library to make a submit button with a nice animation (code below), after pressing the button, a want to start a new activity, but only after the animation is finished, how do i do that?
Xml code for the button "submitButton":
<com.spark.submitbutton.SubmitButton
android:layout_width="200dp"
android:layout_height="200dp"
android:text="Submit"
android:textColor="#color/gray"
app:sub_btn_background="#color/white"
app:sub_btn_duration="3000"
app:sub_btn_line_color="#99FF00"
app:sub_btn_ripple_color="#99FF00"
app:sub_btn_tick_color="#color/white"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:id="#+id/submitButton" />
Submit button for java file and action listener :
SubmitButton submitButton = (SubmitButton) findViewById(R.id.submitButton);
submitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this,ListViewActivity.class));
}
});

If that custom button doesn't provide a listener for its animation, there's no way to know when its animation is done.
Alternatively, you could use the duration of that animation, and start your activity in a postDelayed(runnable, duration)
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
startActivity(new Intent(MainActivity.this,ListViewActivity.class));
}
}, duration);
You may also replace the new Handler() with the v from onClick(View v)

Rather than start the activity directly, wrap up the call in a runnable, and call postDelayed with 3000 ms delay.
Like this
public void onClick(View v) {
Runnable r = new Runnable()
{
public void run()
{
startActivity(new Intent(MainActivity.this,ListViewActivity.class));
}
}
v.postDelayed(r, 3000);
}

Related

Disable button after returning from an intent

Afternoon all I need to call an intent and upon returning disable the button for X seconds.
I have tried variations of the following, which either disable the button immediately and then enable or do not do what I need full stop.
Guarding.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Guarding.setEnabled(false);
SharedPref.write(SharedPref.SCANTYPE,"GUARDING");
Intent intent = new Intent(Menu.this, CmxScanner.class);
startActivity(intent);
Guarding.postDelayed(new Runnable() {
public void run() {
Guarding.setEnabled(true);
//Log.d(TAG,"resend1");
}
},10000);
}
});
So on first entry to the menu i have a button that is enabled, after clicking it must call the intent and upon returning disable the button again for X seconds. Before it will enable and allow a second request to the Intent
You can register your calling activity for a result as explained in the Android docs here. Then in the result callback you simply enable the button after 10 seconds:
ActivityResultLauncher<String> mGetContent = registerForActivityResult(new GetContent(),
new ActivityResultCallback<Uri>() {
#Override
public void onActivityResult(Uri uri) {
Guarding.postDelayed(new Runnable() {
public void run() {
Guarding.setEnabled(true);
}
}, 10000);
}
}
});

Delay between two functions of one method

I am new to Android Studio. I want to put delay between Animation of button AND opening of second activity, So that animation runs and then splashActivity opens.
btn.setOnClickListener(new View.OnClickListener(){
public void onClick(View arg0){
Animation anim4 = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.splash_anim);
btn.startAnimation(anim4);
startActivity(new Intent(MainActivity.this, splashActivity.class));
}
});
int Delay_time_of_animation=500;
btn.setOnClickListener(new View.OnClickListener(){
public void onClick(View arg0){
Animation anim4 = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.splash_anim);
btn.startAnimation(anim4);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
startActivity(new Intent(MainActivity.this, splashActivity.class));
}
}, Delay_time_of_animation);
}
});
I use the native java Timer for the delay. if you want to delay between two method then you have to pass the delay time in milliseconds.
int DELAY_TIME=2000
//start your animation
new Timer().schedule(new TimerTask() {
#Override
public void run() {
//this code will run after the delay time which is 2 seconds.
startActivity(new Intent(MainActivity.this, splashActivity.class));
}
}, DELAY_TIME);
2000 millisecond means 2 second you can increase this time

How to make the java wait for x seconds and then execute

I making an app and I would run in to a problem that I can't fix.
I am using Android Studio and I need to make a Button that I have already made. Do more then it already does. I want it to after display a text also close the app. Do you know how I should program that. It would be very helpful. Thanks in advance.
Here is the Java code:
package test.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void buttonOnClick(View v) {
Button button=(Button) v;
((Button) v).setText("Correct");
}
public void buttonAnClick(View q) {
Button button=(Button) q;
((Button) q).setText("Niet goed");
}
}
So I have already made the button in XML and told it:
android:onClick="buttonOnClick"
Hope you can help me out!
If you're looking to have something happen afterwards what you're looking for is this:
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
//What you want to happen later
}
}, 1500); //1500 = 1.5 seconds, time in milli before it happens.
Put that in your button's method.
If you want to close your app you should call
finish();
Finish closes out the current activity. If you have other activities on the stack you'd return to them but since you likely only have 1 it should take you out.
Try this.
public void buttonOnClick(View v) {
Button button=(Button) v;
((Button) v).setText("Correct");
new android.os.Handler().postDelayed(new Runnable() {
#Override
public void run() {
finish();
}
},1000); // milliseconds: 1 seg.
}
Check out CountDownTimer
CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
mTextField.setText("done!");
}
}.start();
If you are trying to get something done with a delay when a button is pressed then do it something like this:
public void buttonOnClick(View v) {
Button button=(Button) v;
button.setText("Correct");
button.postDelayed(new Runnable(){
public void run() {
//runs after 1 second delay on UI thread
}
}, 1000L);
}
If you want to pause then use java.util.concurrent.TimeUnit.
For example:
TimeUnit.SECONDS.sleep(1);
Just put method into your button click function
public void buttonOnClick(View v) {
//call method here
}
If you want to use RxJava
Disposable di = Observable.timer(2, TimeUnit.SECONDS)
.subscribe(timer->{
//next action after 2 seconds
},throwable->{
// throw exception
});
To destroy disposable use, di.dispose();
if Use Runnable and Handler
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
//next action after 2 seconds
}
}, 2*1000);
to stop the handler use, handler.removeCallbacksAndMessages(null);

Buttons outside the onCreate

Always in my apps I added buttons in void onCreate, but now I'm trying to do app with more buttons (about 10). I would like to all buttons active on start app.
In my opinion it is too much buttons to add in this onCreate and app will be starting to long.
I tried to put this:
myButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
myMethod();
}
})
out of onCreate
but AndroidStudio underlines setOnClickListener and view
I don't have ideas, how and where can i add button out of onCreate.
If you don't want to overcrowd your oncreate method, then create a clicklistener outside onCreate anywhere in activity and in onCreate just set it.
onCreate :
edit_a_member = (Button) findViewById(R.id.edit_member);
delete_a_member = (Button) findViewById(R.id.delete_member);
edit_a_member.setOnClickListener(handleClick);
delete_a_member.setOnClickListener(handleClick);
clickListener:
private View.OnClickListener handleClick = new View.OnClickListener() {
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.edit_member:
member_selected = EDIT_MEMBER_SELECTED;
callDialog();
break;
case R.id.delete_member:
callDeleteAlert();
break;
}
}
};
You can simply add a separate method for your buttons in the same class, e.g.:
public void onCreate(...){
//Standard setup of views or whatever you want to do here
this.addButtons();
}
private void addButtons(){
Button b1 = new Button("Hi");
b1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
myMethod();
}
});
Button b2 = new Button("Hi to you too");
b2.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
myMethod();
}
});
}
This is an example. You can do this in soooo many ways. I feel like you should thoroughly learn Java's fundamental Object Oriented programming, because that's really what your question suggests you don't understand. Go follow a youtube tutorial. I always like "The New Boston"'s Java tutorial series on youtube.
PS: You can make code like this beautiful under the 'Words of wisdom': Don't repeat yourself
If you have to do a lot of work in your onCreate but you are worried that the UI will take too long to load you can always post a delayed runnable to a handler so in the onCreate method put :
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
//add your code here
}
},10);
what this will do is your UI will load then the code in your Runnable will be executed 10 milliseconds after your UI loads thus your app will not take too long to load the UI, even though in your case I doubt it would be necessary.
If you are declaring the buttons in xml file :
Add these properties in each button Declaration in your Xml :
android:clickable="true"
android:onClick="onClick"
And now in Activity Class create a method like this :
public void onClick(View v){
switch(v.getId){
case R.id.{buttons_id_in_xml}
(Your Code)
break;
(Like for others)
}
}
If you want to add buttons dynamically :
Create a method to add the button like this:
void addButton(String buttonName, int button id){
Button button = new Button(this);
button.setText("Push Me");
(add it to parent Layout of xml)
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
switch(id){
case id1:
(handle )
break;
(like for others)
}
}
});
}
The best way to do this is:
add implements View.OnClickListener to
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
// declare variables
private Button mBtn1;
private Button mBtn2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
// make an instance to the btns
mBtn1 = findViewById(R.id.btn1);
mBtn2 = findViewById(R.id.btn2);
// set onClickListener
mBtn1.setOnClickListener(this); // with "this" you are passing the view
mBtn2.setOnClickListener(this);
}
// implement onClick
#Override
public void onClick(View view) {
// check which btn was clicked by id
switch (view.getId()) {
case R.id.btn1:
btn1Clicked();
break;
case R.id.btn2:
btn2Clicked();
break;
}
}
private void btn1Clicked() {
// your code btn1 clicked
}
private void btn2Clicked() {
// your code btn2 clicked
}
Hope this helped. Cheers!

How to restore to exact activity after coming from Paused or Resumed state in android

I have two simple activities MainActivity and ThreadActivity. I call ThreadActivity from MainActivity.
The code ofMainActivity:
public class MainActivity extends Activity {
private Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button)findViewById(R.id.btn2);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ThreadActivity.class);
startActivity(intent);
}
});
}
}
And the code of ThreadActivity:
public class ThreadActivity extends Activity{
private Thread myThread=null;
Button btn;
int i = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.custom);
btn = (Button)findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
runThread();
}
});
}
void runThread(){
myThread = new Thread() {
public void run() {
while (i++ < 1000) {
try {
runOnUiThread(new Runnable() {
#Override
public void run() {
btn.setText("#" + i);
Log.d("Thread", "I am running " + i);
}
});
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
return;
}
}
}
};
myThread.start();
}
}
When I start ThreadActivity I run a simple thread and change button text.
My Problem
When I loose focus from application, i.e when application becomes partially visible, and I come back I am redirected to ThreadActivity and the thread is still running.
When I leave application running and open a new application, and then come back, I am again redirected to ThreadActivity.
The problem is when I press back button, I am being redirected to first activity MainActivity. But instead when back button is being pressed I want my application to exit. In a few words MainActivity should not exist in the stack.
I tried setting android:noHistory="true" for MainActivity but I could not keep the behavior explained in bullet points working. I mean when I pause the application and restore it back, it redirected me to MainActivity instead of ThreadActivity.
Just call finish() when starting the ThreadActivity:
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ThreadActivity.class);
startActivity(intent);
finish();
}
});
BUT there is a problem with your app. Use a Timer to set the text of the Button! By using a Thread like you do you are creating a memory leak and that is very bad. Try this:
private int i = 0;
private Timer timer;
private final TimerTask timerTask = new TimerTask() {
#Override
public void run() {
btn.post(new Runnable() {
#Override
public void run() {
btn.setText("#" + i++);
}
});
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.custom);
btn = (Button)findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
timer = new Timer();
timer.schedule(timerTask, 300, 300);
}
});
}
#Override
public void onPause() {
super.onPause();
if(timer != null) {
timer.cancel();
}
}
From your comments to other peoples' answers, it seems like you want the ThreadActivity to always be resumed instead of the MainActivity when your thread is running.
Do the thread in a Service - the service will mean your application's VM is likely to be kept alive longer. An app with no foreground activities can be killed off quite quickly (even if it has background threads running).
You need to persist that the thread is running, and the progress (if, in the real code that is applicable). Currently you could persist the value of i in your while loop.
Your application's default launcher activity (MainActivity) will launch when you click on it from your launcher. Check if the persisted value has been set, and act as though the user started the ThreadActivity in onCreate, if you finish() in onCreate, the user won't see any UI from the MainActivity
Depending on what you're actually trying to do, you might be able to resume the thread depending on the progress persisted - in this example, you could start from the persisted value of i (instead of 0).
What I had to is set android:noHistory="true" for MainActivity and in the ThreadActivity I had to add the solution mention by #NeTeInStEiN in this quesiotn
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
moveTaskToBack(true);
return true;
}
return super.onKeyDown(keyCode, event);
}

Categories

Resources