Android 我可以将Click Listener添加到自定义Toast吗
我正在为我的应用程序创建自定义toast。我需要的是在我添加在Toast上的按钮上添加OnClickListener。一切都很顺利,我可以看到按钮,但它不响应OnClick。任何想法 示例代码:Android 我可以将Click Listener添加到自定义Toast吗,android,onclicklistener,toast,buttonclick,android-toast,Android,Onclicklistener,Toast,Buttonclick,Android Toast,我正在为我的应用程序创建自定义toast。我需要的是在我添加在Toast上的按钮上添加OnClickListener。一切都很顺利,我可以看到按钮,但它不响应OnClick。任何想法 示例代码: Button button = new Button(getApplicationContext()); button.setText("Click Me"); button.setOnClickListener(new OnClickListener()
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();
此外,我还尝试像这样向按钮添加onTouchListener
button.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
ProgressDialog.show(getApplicationContext(), "Hello", "nothing");
return false;
}
});
但是它也不起作用。您不应该在
烤面包片中包含按钮。只需显示按钮,然后在一段时间后隐藏它。您可以通过在现有布局的上方添加一个RelativeLayout
来实现这一点。像这样的方法应该会奏效:
<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>
然后在onCreate
中,将按钮显示为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);
克劳顿图书馆解决了这个问题。希望这对其他人也有帮助
不要使用toast,而是使用DialogView。toast中的视图不能单击,因此请使用AlertDialog或popupwindow。在toast上使用按钮是个坏主意。使用对话框,但情况并非如此。按钮未收到单击事件。@Adnan是否看到我修改的答案
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);