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
How to set focus to a button widget programmatically?
提问by Vinayak Bevinakatti
Is it possible to set a focus to a button widget which lies somewhere down in my layout? onCreate
of 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 focusable
andfocusableInTouchMode
. Most widgets are focusable
but not focusableInTouchMode
by default. So make sure to either set it in code
重要说明:按钮小部件需要是focusable
和focusableInTouchMode
。大多数小部件是focusable
但不是focusableInTouchMode
默认情况下。所以一定要在代码中设置它
myBtn.setFocusableInTouchMode(true);
or in XML
或 XML
android:focusableInTouchMode="true"
回答by Zan
Try this:
尝试这个:
btn.requestFocusFromTouch();