Reputation: 5075
I am creating a custom toast for my application. What I need is to add OnClickListener on a button I added on Toast. Everything goes well, I can see the button but it does not respond to OnClick. Any idea.
Example Code:
Button button = new Button(getApplicationContext());
button.setText("Click Me");
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
ProgressDialog.show(getApplicationContext(), "Hello", "nothing");
}
});
button.setLayoutParams(new ViewGroup.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT));
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.BOTTOM, 0, 0);
toast.setMargin(0,-80);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(button);
toast.show();
Further, I have tried by adding onTouchListener to button like this.
button.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
ProgressDialog.show(getApplicationContext(), "Hello", "nothing");
return false;
}
});
But it does not work either.
Upvotes: 2
Views: 4642
Reputation: 5075
Crouton library solved the problem. Hope it would be helpful for someone else too.
https://github.com/keyboardsurfer/Crouton
Upvotes: 0
Reputation: 36289
You should not include a Button
in the Toast
. Just show the button, then hide it after a length of time. You can do this by adding a RelativeLayout
over top of your existing layout. Something like this should work:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<include layout="@layout/main" /><!-- References your existing layout file -->
<Button
android:id="@+id/toast_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_alignParentBottom="true"
android:visibility="gone"
android:text="@string/click_me"
android:onClick="showDialog" /><!-- Should reference a String resource "click me"-->
</RelativeLayout>
Now create the Toast effect, add the following method to your Activity
:
public void showDialog(View v) {
if (v.getId() == R.id.toast_button) {
ProgressDialog.show(this, "Hello", "nothing");
}
}
Then in onCreate
, show the button like a Toast
:
final Button b = (Button) findViewById(R.id.toast_button);
//optionally add some animations for fading in
b.setVisibility(View.VISIBLE);
Timer t = new Timer();
t.schedule(new TimerTask() {
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
//optionally add some animations for fading out
b.setVisibility(View.GONE);
}
});
}
}, 1000);
Upvotes: 1