Reputation: 177
I am making an android application in its layout, I have 4 buttons
<Button
style="@style/Tile"
android:id="@+id/button1"
android:onClick="b1"/>
<Button
style="@style/Tile"
android:id="@+id/button2"
android:onClick="b2"/>
<Button
style="@style/Tile"
android:id="@+id/button3"
android:onClick="b3"/>
<Button
style="@style/Tile"
android:id="@+id/button4"
android:onClick="b4"/>
And i want to trigger a method if user does not interact with them within 20 seconds, and also if user interact the method will be different. can you please help me solve this problem, or guide me where should i look for solution.
Upvotes: 1
Views: 731
Reputation: 19427
Define a Runnable
. This will get executed if the Button
will not get clicked in 20 seconds:
final Runnable runnable = new Runnable() {
@Override
public void run() {
// do something
aMethod();
}
};
Create a Handler
and post the Runnable
with a delay of 20 seconds:
final Handler handler = new Handler();
handler.postDelayed(runnable, 20000);
If the Button
gets clicked, call removeCallbacks()
on the Handler
instance, which will effectively remove the pending Runnable
from the Handler
's message queue:
Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
handler.removeCallbacks(runnable);
// do your Button stuff
anotherMethod();
}
});
Upvotes: 2
Reputation: 381
@Jay you can use code which explained by @Stallion Just put performClick method you will be able to click on view
void processAfterDelayed(){
button1.performClick();
}
Upvotes: 1
Reputation: 5655
Below logic will trigger method processAfterDelayed()
after delay specified in Handler once the Activity is pushed. You can modify this logic for your specific requirement!
public class MyActivity extends AppCompatActivity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view);
Handler handlerTimer = new Handler();
handlerTimer.postDelayed(new Runnable() {
public void run() {
processAfterDelayed();
}
}, 1500);
}
void processAfterDelayed(){
//your logic
}
}
Upvotes: 1