tags:

views:

1836

answers:

6

Currently, I have a layout which contains a Button, a TextView and an EditText. When the layout is displayed, the focus will be automatically put on the EditText, which will trigger the keyboard to show up on Android phone. It is not what I want. Is there any way that I can set the focus on TextView or on nothing when a layout is displayed? Thanks.

+3  A: 

Set focus: The framework will handled moving focus in response to user input. To force focus to a specific view, call requestFocus()

mbaird
+1  A: 

I tried requestFocus(), but it doesn't work. See the code below:

public class HelloAndroid extends Activity {
   /** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.main);

       LinearLayout mainVw = (LinearLayout) findViewById(R.id.main_layout);

       LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
               LinearLayout.LayoutParams.FILL_PARENT,
               LinearLayout.LayoutParams.WRAP_CONTENT);

       EditText edit = new EditText(this);
       edit.setLayoutParams(params);
       mainVw.addView(edit);

       TextView titleTv = new TextView(this);
       titleTv.setText("test");
       titleTv.setLayoutParams(params);
       mainVw.addView(titleTv);

       titleTv.requestFocus();
   }
}

The focus still goes to the EditText when the page is displayed. How to make the focus to be on the TextView?

I figured it out. I have to call title.setFocusableInTouchMode(true) before I call titleTv.requestFocus().
No, don't do that. A view that's focusable in touch mode has weird interactions and unless you perfectly understand what you are doing you should NOT use it.requestFocus() works, but focus is shown only when the device is not in touch mode. As soon as the user touches the screen, the focus is not displayed anymore. By doing what you are doing you are making your app behave differently from the rest of the system and you risk weird behaviors.
Romain Guy
But the issue is that requestFocus() in the code above doesn't work. What's you suggestion to change the code?
+1  A: 

Try

comp.requestFocusInWindow();
JamesC
A: 

Set android:focusable="true" in your

ravi
A: 

The last suggestion is the correct solution. Just to repeat, first set android:focusable="true" in the layout xml file, then requestFocus() on the view in your code.

Reza Nezami
A: 

i think a text view is not focusable. Try to set the focus on a button for example, or to set the property focusable to true.

lapakrette