我想編寫一個程序,當我點擊確定按鈕時,在吐司中顯示一條消息,用於點擊該警報對話框的確定按鈕。但是,這種情況變得非常不同。我不知道我應該把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();
}
}
您是否嘗試過使用getApplicationContext()或MainActivity.this,或者在傳遞上面的參數作爲參數時是否收到任何錯誤? –
我已經發布了答案,請檢查它,並讓我知道它是否工作 –
如果它的工作,接受答案或upvote它 –