Android 如何在警报对话框中显示toast消息?
我想写一个程序,这样当我点击Ok按钮时,会在toast中显示一条消息,用于点击警报对话框的Ok按钮。但事实证明,这起案件完全不同。我不知道在makeText()中应该把什么作为第一个参数。 显然,“this”不是参数上下文所需的参数。 这是我写的代码:Android 如何在警报对话框中显示toast消息?,android,android-alertdialog,toast,Android,Android Alertdialog,Toast,我想写一个程序,这样当我点击Ok按钮时,会在toast中显示一条消息,用于点击警报对话框的Ok按钮。但事实证明,这起案件完全不同。我不知道在makeText()中应该把什么作为第一个参数。 显然,“this”不是参数上下文所需的参数。 这是我写的代码: package com.example.spinner; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInt
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();
}
}
替换这个
Toast.makeText(this, "You selected OK", Toast.LENGTH_SHORT).show();
与
您是否尝试过使用getApplicationContext()或MainActivity。这或您在将上述参数作为参数传递时是否遇到任何错误。我已发布了答案,请检查它并让我知道它是否有效,因为我正在使用另一个类MyListener MainActivity。这不起作用。您是否收到警报框?是,我去拿警报箱。
Toast.makeText(YourActivity.this, "You selected OK", Toast.LENGTH_SHORT).show();
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();
Toast.makeText(MainActivity.this,"You selected ok",Toast.LENGTH_SHORT);