当前位置: 动力学知识库 > 问答 > 编程问答 >

android - How to requestFocus on EditText from onClick function of button?

问题描述:

This is my code.

Focus is not coming on EditText(named search). And I don't have any other EditText in the current layout.

 handle.setOnClickListener(new OnClickListener() {

@Override

public void onClick(View v) {

search.requestFocus();

}

});

网友答案:

See the codes:

public class MainActivity extends ActionBarActivity implements View.OnClickListener {
private EditText text1;
private EditText text2;
private Button button1;
private Button button2;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    text1 = (EditText)findViewById(R.id.editText);
    text2 = (EditText)findViewById(R.id.editText2);
    button1 = (Button)findViewById(R.id.button);
    button2 = (Button)findViewById(R.id.button2);
    button1.setOnClickListener(this);
    button2.setOnClickListener(this);
}
@Override
public void onClick(View view) {
    if(view.getId() == R.id.button){
        text1.requestFocus();
    }
    else if(view.getId() == R.id.button2){
        text2.requestFocus();
    }
}
}

The requestFocus() is enough.No additional attributes "focusable" set,the EditText was added as default behavior. May you forget add like "button1.setOnClickListener(this);" to make the button responsible?

网友答案:

Try adding this code to your xml!

<EditText
      android:focusable="true"
      <requestFocus />
</EditText>
网友答案:

If you want your Keyboard to popup then try this code

EditText myEditText = (EditText) findViewById(R.id.search);
((InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE))
    .showSoftInput(myEditText, InputMethodManager.SHOW_FORCED);

Also add in your Mainfest

<activity android:name=".first" android:windowSoftInputMode="stateAlwaysVisible">

网友答案:

you should use

    search.setFocusable(true);
    search.requestFocus();
分享给朋友:
您可能感兴趣的文章:
随机阅读: