모든 요청에 따라 동적으로 변화하는 텍스트가있는 Android AlertDialog
-
11-09-2019 - |
문제
모든 요청에서 변경 될 수있는 하나의 옵션이있는 AlertDialog를 보여주고 싶습니다. 예를 들어, 한 번에 "연락처에 추가"옵션을 표시하고 다른 시간에는 "연락처에서 제거"해야합니다.
내 코드는 처음으로 작동하지만 Android는 AlertDialog를 캐시하여 다음에 실행되지 않도록합니다. 따라서 옵션은 더 이상 변경되지 않습니다. 이 캐싱을 방지 할 수 있습니까? 아니면 옵션을 변경하는 다른 방법 만 있습니까?
SDK 1.5와 함께 일하고 있지만 1.1을 사용하고 있습니다.
@Override
protected Dialog onCreateDialog(final int id) {
...
String add_remove_contact = res.getString(R.string.profile_add_to_contacts);
if (user.getContacts().contains(profileID)) {
add_remove_contact = res.getString(R.string.profile_remove_from_contacts);
// TODO: this string is not changed when contact status changes
}
final CharSequence[] items = {res.getString(R.string.view_profile),
res.getString(R.string.profile_send_message),
add_remove_contact};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
...
return builder.create();
}
해결책
당신은 또한 사용할 수 있습니다 removedialog (int) 활동의 기능. 대화 상자가 기각되면, 활동은 기본적으로 대화의 상태를 저장합니다 (공연상의 이유로 상상할 수 있습니다). 부름 removedialog (int) 대화 상자에서 활동은 대화 상자에 대한 모든 참조를 언로드하고 표시되는 경우 화면에서 기각합니다.
다른 팁
보세요 onpreparedialog 대화 상자가 표시되기 전에 호출되는 메소드가 표시됩니다. 요청 유형에 따라 필요한 값을 변경할 수 있습니다.
날짜 선택기의 예
@Override
protected Dialog onCreateDialog(final int id) {
switch (id) {
case DIALOG_DATE_ID:
final Calendar c = Calendar.getInstance();
return new DatePickerDialog(this, this, c.get(Calendar.YEAR),
c.get(Calendar.MONTH),
c.get(Calendar.DAY_OF_MONTH));
default:
return super.onCreateDialog(id);
}
}
@Override
protected void onPrepareDialog(final int id, final Dialog dialog) {
switch (id) {
case DIALOG_DATE_ID:
//update to current time
final Calendar c = Calendar.getInstance();
((DatePickerDialog) dialog).updateDate(c.get(Calendar.YEAR),
c.get(Calendar.MONTH),
c.get(Calendar.DAY_OF_MONTH));
break;
}
}
이것은이 질문의 DUP입니다.Android : AlertDialog에 텍스트를 변경할 수 없습니다.
이런 식으로 할 수도 있습니다.http://andmobidev.blogspot.com/2010/03/modifying-alert-dialogs-list-items.html
그래도 Longpress 메뉴의 표시 속도를 늦추는 것 같습니다 ...
위에서 언급 한 일관되지 않은 행동에 대한 수정이 있다고 생각합니다. 처음에 대화 상자를 만들 때 (여전히 AlertDialog.Builder 일 때) 메시지를 초기 상태 (NULL)로 설정해야합니다. 그렇지 않으면 OnPreparedialog가 의도 된 값으로 덮어 쓰지 않습니다. 따라서 대화 상자를 만들 때 메시지에 항상 널 값이 아닌 값을 갖도록 이와 같은 작업을 수행하십시오. 나는 이것으로 며칠 동안 어려움을 겪고 우연히이 솔루션을 발견했습니다.
AlertDialog.Builder resultAlert = new AlertDialog.Builder(context);
if ( message == null ) {
resultAlert.setMessage("");
} else {
resultAlert.setMessage(message);
}
활동 관리 대화 상자를 사용하는 성능 이유를 이해하지만 간단한 경우를 제외하고는 사용하지 않는 것이 좋습니다. 그 이유는 다음과 같습니다.
번들 인수는 API 레벨 8에만 추가되었으므로 거꾸로 호환성을 위해 채택 할 수 없습니다. 이것은 효과적으로 'onpreparedialog'가 상태 차이에 대한 비 국한 변수에 의존해야 함을 의미합니다.
실습은 'onpreparedialog'의 본문에서 이루어진 대화 변경에 대한 반응으로 열악하고 일관되지 않은 행동을 나타냅니다.
대화 상자가 필요에 따라 서브 클래스 및 생성되는 경우 이러한 어려움은 발생하지 않습니다. 필요한 경우 'setownerActivity'를 호출 할 수 있습니다.
사용자 정의 대화 상자가 있으면 Dialog.getWindow ()를 사용하여 사용자 정의 항목을 변경할 수 있습니다. findViewById (...)
이 예제는 마지막 텍스트를 저장하고 다음에 대화 상자를 표시 할 때 다시 표시합니다.
// custom dialog
final Dialog dialog = new Dialog(this);
dialog.setContentView(R.layout.customized);
dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialogInterface) {
EditText dialogText = (EditText)dialog.getWindow().findViewById(R.id.customText);
savedText = dialogText.getText();
}
});
dialog.show();
EditText dialogText = (EditText)dialog.getWindow().findViewById(R.id.customText);
dialogText.setText(savedText);
사용자 정의 대화 상자의 XML :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/buttonOK"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="OK"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="16dp" />
<EditText
android:id="@+id/customText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="19dp"
android:hint="Message"
android:ems="10"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
그리고 나는 아이디어를 얻었지만 그렇게 좋지는 않습니다.*사용자가 대화 상자를 자주 사용하지 않을 때 사용됩니다!*솔루션 : 먼저 변수 (int 유형)를 선언하고 기본값을 0.such로 만들어야합니다. private int i=0;
ShowDialog 활동 방법을 사용하기 전에 int 변수 i를 늘리고 값을 ShowDialog 메소드로 매개 변수로 게시하십시오. 코드는 이것을 좋아할 수 있습니다
private int i=0;
//before you show the dialog
this.i++;
this.showDialog(this.i);
바로 그거죠. AlertDialog의 경우, 그것은 다음과 같이 만들어졌습니다. Builder.create()
, onPrepareDialog()
쓸모가 없습니다. Builder는 대화 상자가 생성되면 업데이트 할 수 없다는 점에서 일방 통행입니다. 내 말은 느슨하게 말할 수 없다는 것을 의미합니다. 나는 당신이보기를 처리하고 수동으로 모든 것을 할 수 있다고 확신하지만, 처음에는 빌더를 사용하는 지점을 물리칩니다.
내가 찾은 유일한 해결책은 사용하는 대신 대화 상자를 수동으로 작성 / 표시 / 해고하는 것이 었습니다. onCreateDialog()
, showDialog()
, 등. 나는 전화를 시도했다 removeDialog()
, 그러나 그것은 효과가없는 것 같습니다.