2014-02-20 85 views
2

我正在爲我的應用程序創建自定義Toast。我需要的是在Toast上添加的按鈕上添加OnClickListener。一切順利,我可以看到按鈕,但它不響應OnClick。任何想法。我可以將Click Listener添加到自定義Toast中

例如代碼:

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

但它也不起作用。

+1

,而不是烤麪包用一個對話框 – Raghunandan

+0

視圖不會點擊的內部吐司所以使用AlertDialog或popupwindow。 –

+0

使用烤麪包上的按鈕是個不錯的主意。使用對話框 – JesusS

回答

1

您不應該在Toast中包含Button。只需顯示按鈕,然後在一段時間後隱藏它。您可以通過在現有佈局上添加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> 

現在創建吐司效果,添加下面的方法到您Activity:在onCreate

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

然後,顯示按鈕一個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); 
+0

Phil並非如此。按鈕不會收到點擊事件。 – Adnan

+0

@Adnan看到我修改後的答案 – Phil

相關問題