開始接觸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實作接口,擷取資料。