use*_*101 2 android android-edittext
我想在android edittextpreference上放一个按钮.我创建了一个自定义editextpreference:
public class EditTextPreferenceWithButton extends EditTextPreference {
private Context context;
public EditTextPreferenceWithButton(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
this.context=context;
}
public EditTextPreferenceWithButton(Context context, AttributeSet attrs) {
super(context, attrs);
this.context=context;
}
public EditTextPreferenceWithButton(Context context) {
super(context);
this.context=context;
}
@Override
protected void onBindDialogView(View view) {
super.onBindDialogView(view);
view.setLayoutParams(new LayoutParams(android.view.ViewGroup.LayoutParams.WRAP_CONTENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT));
final EditText editText = (EditText)view.findViewById(android.R.id.edit);
ViewGroup vg = (ViewGroup)editText.getParent();
Button button = new Button(context);
vg.addView(button,ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
}
}
Run Code Online (Sandbox Code Playgroud)
通过这种方式,按钮显示在编辑文本下方,但我希望它是下一个edittext,如下所示:
|的EditText | |按钮|
请帮我!谢谢
我会创建一个子类DialogPreference.
class EditTextDialogPreference extends DialogPreference {
//Layout Fields
private final LinearLayout layout = new LinearLayout(this.getContext());
private final EditText editText = new EditText(this.getContext());
private final Button button = new Button(this.getContext());
//Called when addPreferencesFromResource() is called. Initializes basic paramaters
public EditTextDialogPreference(Context context, AttributeSet attrs) {
super(context, attrs);
setPersistent(true);
button.setText("Button");
layout.setOrientation(LinearLayout.HORIZONTAL);
}
//Create the Dialog view
@Override
protected View onCreateDialogView() {
layout.addView(editText);
layout.addView(button);
return parentLayout;
}
//Attach persisted values to Dialog
@Override
protected void onBindDialogView(View view) {
super.onBindDialogView(view);
editText.setText(getPersistedString("EditText"), TextView.BufferType.NORMAL);
}
//persist values and disassemble views
@Override
protected void onDialogClosed(boolean positiveresult) {
super.onDialogClosed(positiveresult);
if (positiveresult && shouldPersist()) {
persistString(editText.getText().toString());
}
((ViewGroup) editText.getParent()).removeView(editText);
((ViewGroup) button.getParent()).removeView(button);
((ViewGroup) layout.getParent()).removeView(layout);
notifyChanged();
}
}
Run Code Online (Sandbox Code Playgroud)
我假设你要继续保持价值EditText,我将按钮的动作留给你.有关扩展的输入和输出的更多信息,请参阅此文章DialogPreference.
为了获得密钥SharedPreferences,请将以下内容放入XML中:
<com.yourpackage.EditTextDialogPreference
android:key="Your Key"
android:persistent="true"/>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2687 次 |
| 最近记录: |