stackoverflow.com/a/33842737
нь плохо знаком с Android, и я пытаюсь загрузить / сохранить значения из моего настроенного DialogPreference. В настоящее время это не удается, так как findViewById возвращает значение NULL. Это способ, которым я (пытаюсь) сделать это правильно? Как получить доступ к моим виджетам EditText в коде?
public class AddressDialogPreference extends DialogPreference {
public AddressDialogPreference(Context context, AttributeSet attrs) {
super(context, attrs);
setDialogLayoutResource(R.layout.address_dialog);
}
@Override
protected void onBindDialogView(View view) {
EditText idField = (EditText) view.findViewById(R.id.hostID);
EditText ipField = (EditText) view.findViewById(R.id.hostIP);
SharedPreferences pref = getSharedPreferences();
idField.setText(pref.getString(getKey() + "_id","ExampleHostname"));
ipField.setText(pref.getString(getKey() + "_ip","192.168.1.1"));
super.onBindDialogView(view);
}
@Override
protected void onDialogClosed(boolean positiveResult) {
if(!positiveResult)
return;
Dialog myDial = getDialog();
EditText idField = (EditText) myDial.findViewById(R.id.hostID);
EditText ipField = (EditText) myDial.findViewById(R.id.hostIP);
SharedPreferences.Editor editor = getEditor();
editor.putString(getKey() + "_id",idField.getText().toString());
editor.putString(getKey() + "_ip",ipField.getText().toString());
}
address_dialog.xml:
<TextView
android:text="Insert IP address"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/hostIP" />
<TextView
android:text="Insert identifier"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/hostID" />