Tuesday, September 27, 2016

android - Select all text inside EditText on focus

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/coordinator_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#efeeea"
    >
    <!--
        android:selectAllOnFocus
            If the text is selectable, select it all when the view takes focus.
            Must be a boolean value, either "true" or "false".

            This may also be a reference to a resource (in the form "@[package:]type:name") or
            theme attribute (in the form "?[package:][type:]name") containing a value of this type.

            This corresponds to the global attribute resource symbol selectAllOnFocus.
    -->
    <EditText
        android:id="@+id/et"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="top|center_horizontal"
        android:textSize="25sp"
        android:padding="5dp"
        android:layout_marginTop="50dp"
        android:text="Hello Android."
        android:selectAllOnFocus="true"
        />
</android.support.design.widget.CoordinatorLayout>

2. Select all text inside EditText on focus programmatically

MainActivity.java

package com.cfsuman.me.androidcodesnippets;

import android.app.Activity;
import android.content.Context;
import android.support.design.widget.CoordinatorLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.EditText;


public class MainActivity extends AppCompatActivity {
    private Context mContext;
    private Activity mActivity;

    private CoordinatorLayout mCLayout;
    private EditText mEditText;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Get the application context
        mContext = getApplicationContext();
        mActivity = MainActivity.this;

        // Get the widget reference from XML layout
        mCLayout = (CoordinatorLayout) findViewById(R.id.coordinator_layout);
        mEditText = (EditText) findViewById(R.id.et);

        /*
            setSelectAllOnFocus
                void setSelectAllOnFocus (boolean selectAllOnFocus)

                Set the EditText so that when it takes focus, all the text is selected.
        */

        // Select all text inside EditText when it gets focus
        mEditText.setSelectAllOnFocus(true);
    }
}