2015-09-19 139 views
0

我想編寫一個程序,當我點擊確定按鈕時,在吐司中顯示一條消息,用於點擊該警報對話框的確定​​按鈕。但是,這種情況變得非常不同。我不知道我應該把makeText()作爲第一個參數。 顯然,'this'不是參數上下文所需的參數。 這是我寫的代碼:如何在警報對話框中顯示Toast消息?

package com.example.spinner; 

    import android.app.Activity; 
    import android.app.AlertDialog; 
    import android.content.DialogInterface; 
    import android.content.DialogInterface.OnClickListener; 
    import android.os.Bundle; 
    import android.view.Menu; 
    import android.view.MenuItem; 
    import android.view.View; 
    import android.widget.Toast; 

    public class MainActivity extends Activity { 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
} 

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.main, menu); 
    return true; 
} 

@Override 
public boolean onOptionsItemSelected(MenuItem item) { 
    // Handle action bar item clicks here. The action bar will 
    // automatically handle clicks on the Home/Up button, so long 
    // as you specify a parent activity in AndroidManifest.xml. 
    int id = item.getItemId(); 
    if (id == R.id.action_settings) { 
     return true; 
    } 
    return super.onOptionsItemSelected(item); 
} 

public void click (View v) 
{ 
    AlertDialog.Builder ad= new AlertDialog.Builder(this); 
    ad.setTitle("Alert Window"); 
    ad.setIcon(R.drawable.ic_launcher); 
    ad.setMessage("This is an alert dialog box"); 
    MyListener m= new MyListener(); 
    ad.setPositiveButton("OK", m); 
    ad.show(); 
} 
} 

    class MyListener implements OnClickListener { 

public void onClick(DialogInterface dialog, int which) { 

    Toast.makeText(this, "You selected OK", Toast.LENGTH_SHORT).show(); 

} 

    } 
+0

您是否嘗試過使用getApplicationContext()或MainActivity.this,或者在傳遞上面的參數作爲參數時是否收到任何錯誤? –

+0

我已經發布了答案,請檢查它,並讓我知道它是否工作 –

+0

如果它的工作,接受答案或upvote它 –

回答

0

替換此

Toast.makeText(this, "You selected OK", Toast.LENGTH_SHORT).show(); 

Toast.makeText(YourActivity.this, "You selected OK", Toast.LENGTH_SHORT).show(); 
0
AlertDialog ad= new AlertDialog.Builder(MainActivity.this).create(); 
    ad.setTitle("Alert Window"); 
    ad.setIcon(R.drawable.ic_launcher); 
    ad.setMessage("This is an alert dialog box"); 
    ad.setButton("OK", new DialogInterface.OnClickListener() { 

     public void onClick(DialogInterface dialog, int which) { 
      // TODO Auto-generated method stub 
      Toast.makeText(MainActivity.this, "You selected OK", Toast.LENGTH_SHORT).show(); 
       } 
      }); 
    //ad is the object reference 
      ad.show(); 
0

Toast.makeText(MainActivity.this, 「您選擇確定」,吐司.LENGTH_SHORT);