Andrii Chernenko
Andrii Chernenko

Reputation: 10204

Setting focus to child EditText when clicking TableRow

I have the following layout:

<TableLayout 
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:stretchColumns="*">

    <TableRow
        android:clickable="true"
        android:focusable="true"
        android:focusableInTouchMode="true"
        android:descendantFocusability="beforeDescendants">

        <TextView
            android:text="Login:"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>

        <EditText
            android:id="@+id/password"
            android:background="@null"
            android:duplicateParentState="true"
            android:inputType="text"
            android:maxLines="1"
            android:singleLine="true"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>           
    </TableRow>
</TableLayout> 

My EditText takes half of screen width, and I want it to take focus when TableRow is clicked. How do I set things up for that? It is it possible without any additional code?

Upvotes: 1

Views: 1107

Answers (1)

Andrii Chernenko
Andrii Chernenko

Reputation: 10204

I ended up implementing a listener. I changed layout a bit:

<TableRow
    android:onClick="focusChildEditText">
    ...

    <EditText
        ...
        android:tag="focusable"/>  

</TableRow>

and used the following listener:

public void focusChildEditText(View view) {
    try {
        EditText editText=((EditText) ((ViewGroup) view).findViewWithTag("focusable"));
        if (editText!=null) 
            editText.requestFocus();
    } catch (ClassCastException e) {}
}

And everything works as I need.

Upvotes: 1

Related Questions