其中(l,t)代表着左上角的位置,(r,b)代表着右下角的位置。
使用案例,如下这个页面:该页面有多个view可以获取焦点,并在获取到焦点的view上赋予一个焦点框。
刚开始实现这个页面的时候使用切图的方法,也就是把每个view的焦点框切一个图,放在
<selector xmlns:android="http://schemas.android.com/apk/res/android" > <!--focus_img:焦点框图片--> <item android:state_focused="true" android:drawable="@drawable/focused_img"/> <item android:state_selected="true" android:drawable="@drawable/focused_img"/> <item android:state_pressed="true" android:drawable="@drawable/focused_img"></item> <item android:drawable="@drawable/unfocused_img"/> </selector>
思路:
1)提供一个.9图片的焦点框
2)提供一个ImageView,这个ImageView的src就是.9图片,假设该ImageView的变量名为focusImgView
3)对页面focusable为true的view设置FoncusChangeListener,如果某个view获取焦点的话,获取该view的左上角的位置(x,y)和它的宽度(width,height).然后设置
focusImgView.layout(x,y,x+width,y+height)(因为android中没有直接的方法来获取某个view右下角的位置,所以需要通过宽和高来计算之)
基本的代码如下:
/**焦点框View**/ public class FocusView extends ViewGroup{ /**焦点框**/ private ImageView focusImgView; /**页面中获取焦点的view**/ private View focusView; /*焦点.9图片*/ private Drawable mViewFocusDrawable; public FocusView(Context context,Drawable mViewFocusDrawable) { super(context); init(mViewFocusDrawable); } private void init(Drawable mViewFocusDrawable) { focusImgView = new ImageView(getContext()); ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); addView(focusImgView, params); focusImgView.setBackgroundDrawable(mViewFocusDrawable); } /** * 设置焦点的图片 * @param d */ public void setFocusDrawable(Drawable mViewFocusDrawable) { focusImgView.setBackgroundDrawable(mViewFocusDrawable); } /* *@focusView 获取焦点的view */ public void showFocus(View focusView) { int[] location = new int[2]; focusView.getLocationInWindow(location); int x = location[0]; int y = location[1]; int width = focusView.getWidth(); int height = focusView.getHeight(); //这是重点步骤 focusImgView.layout(x, y,x+ width,y + height); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { } }
在onFoucusChange方法里面这么调用: @Override public void onFocusChange(View view, boolean hasfocus) { int viewId = view.getId(); switch (viewId) { case R.id.demo_btn: if (hasfocus) { mFocusView.showFocus(view); } break; } }
原文地址:http://blog.csdn.net/chunqiuwei/article/details/45225187