pmcs management
pmcs management

Reputation: 45

EditText with default value

I use bootstrap with an .input-group-addon to prepend or append elements to a single form element like the TextArea input type of form. Prepend simple means it shows it contains value disabled from editing by a user.

How can I do this in my andriod app? It is with my XML or what? Please help...

Upvotes: 2

Views: 6709

Answers (2)

Chintan Rathod
Chintan Rathod

Reputation: 26034

I think following code will help you to do so.

Solution 1

TextView will show only prefix text, and EditText can be of user's choice.

<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>

In above layout, you will see TextView having your default text, but user is only able to write in EditText. So user will not have any idea about such trick.

Solution 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());
        }
    }
});

This solution will not allow user to remove "http://" from its EditText input.

Upvotes: 5

Murtaza Khursheed Hussain
Murtaza Khursheed Hussain

Reputation: 15336

EditText extends TextView which extend View class. And View.java class has method setText which pretty much works for every view which extends View.java.

Conclustion

EditText.setText("your Text here"); //set default value

EditText.setHint("your Text here"); //set hint

In Xml

 android:text="@string/yourStringText"

Upvotes: 3

Related Questions