开始接触java与android,实现了第一个功能:自定义AlertDialog。先上代码:
public void jsmethod_showAlert(final UZModuleContext moduleContext){
final AlertDialog biuAlert = new AlertDialog.Builder(context()).create();
final JSONObject ret = new JSONObject();
int layoutId = UZResourcesIDFinder.getResLayoutID("alert_test");
View testLayout = View.inflate(context(), layoutId, null);
int btnId1 = UZResourcesIDFinder.getResIdID("nBtn");
Button btn1 = (Button) testLayout.findViewById(btnId1);
int btnId2 = UZResourcesIDFinder.getResIdID("oBtn");
Button btn2 = (Button) testLayout.findViewById(btnId2);
String text1 = (String) btn1.getText();
String text2 = (String) btn2.getText();
btn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
biuAlert.cancel();
/*
try{
ret.put("buttonIndex", 2);
moduleContext.success(ret, true);
} catch(Exception e) {
try {
ret.put("err", "errbtn1");
moduleContext.success(ret, true);
} catch(JSONException e1) {
e1.printStackTrace();
}
e.printStackTrace();
}
*/
}
});
btn2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
biuAlert.cancel();
/*
Toast.makeText(context(), "btn2", Toast.LENGTH_SHORT).show();
JSONObject ret2 = new JSONObject();
try{
ret2.put("buttonIndex", 1);
moduleContext.success(ret2, true);
} catch(Exception e) {
try {
ret2.put("err", "errbtn2");
moduleContext.success(ret2, true);
} catch(JSONException e1) {
e1.printStackTrace();
}
e.printStackTrace();
}
*/
}
});
biuAlert.setCancelable(false);
biuAlert.setView(testLayout);
biuAlert.show();
}
遇到几个坑,做下记录:
1. 创建alert的方式
final AlertDialog biuAlert = new AlertDialog.Builder(context()).create();
// final AlertDialog.Builder biuAlert = new AlertDialog.Builder(context());
最开始用的注释的方式创建,但在点击事件中关闭alert时,调用cancel()或dismiss()方法,代码一直显示红色,表示错误。
2. 加载自定义alert内容的布局
View testLayout = View.inflate(context(), layoutId, null);
//LinearLayout testLayout = (LinearLayout) mContext.findViewById(layoutId);
最开始用的注释的方式创建,但后文通过testLayout和findViewById查找其中的控件,一直返回null,表示找不到控件。
3. 控件点击事件
最开时为控件注册点击事件,点击无效
btn1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
4. 与打开前的activity传递数据
在alert的类中定义接口,在打开前的activity实现接口,获取数据。