Android 如何以编程方式将焦点设置到按钮小部件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3234607/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 09:15:10  来源:igfitidea点击:

How to set focus to a button widget programmatically?

androidandroid-widgetandroid-button

提问by Vinayak Bevinakatti

Is it possible to set a focus to a button widget which lies somewhere down in my layout? onCreateof the activity my control/focus should be on that button programmatically.

是否可以将焦点设置到位于布局中某处的按钮小部件?onCreate我的控制/焦点应该以编程方式放在该按钮上。

回答by Pentium10

Yeah it's possible.

是的,这是可能的。

Button myBtn = (Button)findViewById(R.id.myButtonId);
myBtn.requestFocus();

or in XML

或 XML

<Button ...><requestFocus /></Button>

Important Note:The button widget needs to be focusableandfocusableInTouchMode. Most widgets are focusablebut not focusableInTouchModeby default. So make sure to either set it in code

重要说明:按钮小部件需要是focusablefocusableInTouchMode。大多数小部件是focusable但不是focusableInTouchMode默认情况下。所以一定要在代码中设置它

myBtn.setFocusableInTouchMode(true);

or in XML

或 XML

android:focusableInTouchMode="true"

回答by Zan

Try this:

尝试这个:

btn.requestFocusFromTouch();