我想创建一个包含应用程序所有警报的java类。我想让方法保持静态,以便更容易调用。这是我的代码。
警报类
public class Alerts {
// Player has not selected a team
public static void noPlayerTeam(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(view);
builder.setMessage("Select your team.");
builder.setCancelable(true);
builder.setNeutralButton(
"Okay",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog a = builder.create();
a.show();
}
}
隐藏代码
Alerts.noPlayerTeam(view);
文档显示AlertDialog.Builder(Context context)
我正在努力将活动的上下文传递给Alert类。上面代码的错误是错误:(13,63)错误:不兼容的类型:视图无法转换为上下文。
我知道代码有效,因为我可以在与活动相同的脚本中执行它。
答案 0 :(得分:3)
使用view.getContext()
代替view
:
AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
需要将有效的Context( UI Context )传递给Builder构造函数以获取AlertDialog
实例。
答案 1 :(得分:0)
@RunWith(SpringRunner.class)
@WebMvcTest(PersonSerlvet.class)
public class PersonTests {
@Autowired
private MockMvc mvc;
@Test
public void testExample() throws Exception {
this.mvc.perform(get("/person"))
.andExpect(status().isOk());
}
}
Constant
public static void alertDialogShow(Context context, String message)
{
final AlertDialog alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setMessage(message);
alertDialog.setButton("OK", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
alertDialog.dismiss();
}
});
alertDialog.show();
}
Activity
答案 2 :(得分:0)
public class Alert {
// Alert with Message and ok
public static void showAlertDialog(Context context,String title ,String msg){
AlertDialog.Builder builder=new AlertDialog.Builder(context);
builder.setTitle(title);
builder.setMessage(msg);
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}});
builder.create().show();
}
// Alert with Message and ok Click Event
public static void showAlertDialog(Context context, String title ,String msg, DialogInterface.OnClickListener listener){
AlertDialog.Builder builder=new AlertDialog.Builder(context);
builder.setTitle(title);
builder.setMessage(msg);
builder.setPositiveButton("OK", (DialogInterface.OnClickListener) listener);
builder.setNegativeButton("Cancel",(DialogInterface.OnClickListener) listener);
builder.create().show();
}
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Alert.showAlertDialog(this,"Testing","Demooo");
Alert.showAlertDialog(this,"Testing","Demoooooo", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (which==DialogInterface.BUTTON_POSITIVE) {
//Your Code
}else
{
//Your Code
}
}});
}
}