EditText具有默认值

pmc*_*ent 2 android android-layout android-activity

我使用带有.input-group-addon的bootstrap将元素前置或附加到单个表单元素,如TextArea输入类型的表单.前置简单意味着它显示它包含禁止用户编辑的值.

我怎么能在我的andriod应用程序中执行此操作?它与我的XML或什么?请帮忙...

Chi*_*hod 5

我认为以下代码可以帮助您这样做.

解决方案1

TextView将仅显示前缀文本,并且EditText可以由用户选择.

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:background="@android:color/white" >

    <TextView
        android:id="@+id/txtTitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="http://"
        android:textColor="@android:color/darker_gray" />

    <EditText 
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/white"
        android:text="www.google.com"
        />
</LinearLayout>
Run Code Online (Sandbox Code Playgroud)

在上面的布局中,您将看到TextView具有默认文本,但用户只能写入EditText.所以用户不会对这种技巧有所了解.

解决方案2

final EditText edt = (EditText) findViewById(R.id.editText1);

edt.setText("http://");
Selection.setSelection(edt.getText(), edt.getText().length());


edt.addTextChangedListener(new TextWatcher() {

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        // TODO Auto-generated method stub

    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count,
            int after) {
        // TODO Auto-generated method stub

    }

    @Override
    public void afterTextChanged(Editable s) {
        if(!s.toString().contains("http://")){
            edt.setText("http://");
            Selection.setSelection(edt.getText(), edt.getText().length());
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

此解决方案不允许用户从其EditText输入中删除"http://" .