我想编写一个程序,当我单击“确定”按钮时,会在烤面包中显示一条消息,用于单击该警告对话框的“确定”按钮。但是,这个案子结果却大相径庭。我不知道应该把什么作为makeText()中的第一个参数。 显然'this'不是参数上下文的理想参数。 这是我写的代码:
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 :(得分:0)
替换此
Toast.makeText(this, "You selected OK", Toast.LENGTH_SHORT).show();
与
Toast.makeText(YourActivity.this, "You selected OK", Toast.LENGTH_SHORT).show();
答案 1 :(得分: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();
答案 2 :(得分:0)
Toast.makeText(MainActivity.this,"You selected ok",Toast.LENGTH_SHORT);