2

我正在为我的应用程序创建自定义吐司。我需要的是在我在 Toast 上添加的按钮上添加 OnClickListener。一切顺利,我可以看到按钮,但它不响应 OnClick。任何想法。

示例代码:

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;
    }
});

但它也不起作用。

4

2 回答 2

1

你不应该ButtonToast. 只需显示按钮,然后在一段时间后将其隐藏。您可以通过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>

现在创建Toast效果,将以下方法添加到您的Activity

public void showDialog(View v) {
    if (v.getId() == R.id.toast_button) {
        ProgressDialog.show(this, "Hello", "nothing");
    }
}

然后在 中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);
于 2014-02-20T16:08:52.780 回答
0

Crouton 库解决了这个问题。希望它对其他人也有帮助。

https://github.com/keyboardsurfer/Crouton

于 2014-02-20T18:41:40.857 回答