设置控件的高度方法, 宽度类似:
public static void setHeightInPx(View view, int height) { LayoutParams params = view.getLayoutParams(); params.height = height; view.setLayoutParams(params); }
移动EditText的光标到文本结尾:
public static void moveCursor2End(EditText edt_content) { try { CharSequence text = edt_content.getText(); if (text instanceof Spannable) { Spannable spanText = (Spannable) text; Selection.setSelection(spanText, text.length()); } } catch (Exception e) { } }
获取控件Measure的高度, 用于控件还没初始化的时候, 比如onCreate中; 宽度类似:
public static int getMeasureHeight(View view) { int w = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED); int h = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED); view.measure(w, h); return view.getMeasuredHeight(); }
public static void setSearchBarDelay(final EditText edt_search, final OnClickListener listener, View btn_clear) { try { if (edt_search == null) return; edt_search.addTextChangedListener(new TextWatcher() { private long latestTime = 0; private Handler handler = new Handler(); private int delayMills = 1000; @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // 最新输入的时间 latestTime = System.currentTimeMillis(); // 发送查询请求 handler.postDelayed(new Runnable() { @Override public void run() { long currTime = System.currentTimeMillis(); // 如果经过该延迟时间还没有新输入则搜索 if ((currTime - latestTime) < (delayMills - 10)) return; else { listener.onClick(null); } } }, delayMills); } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void afterTextChanged(Editable s) { } }); if (btn_clear == null) return; btn_clear.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { edt_search.setText(""); } }); } catch (Exception e) { LogUtil.d("", e.getMessage()); } }
private static <T> void findViewsByClass(ViewGroup root, ArrayList<T> views, Class<T> targetView) { try { if (root == null) return; int count = root.getChildCount(); View view; for (int i = 0; i < count; i++) { view = root.getChildAt(i); // 判断名称是否一致 if (view.getClass().getName().equals(targetView.getName())) views.add((T) view); // 如果是容器 递归 if (view instanceof ViewGroup) { findViewsByClass((ViewGroup) view, views, targetView); } } } catch (Exception e) { LogUtil.d("", e.getMessage()); } }
dp转为px:
public static int dip2px(Context context, float dpValue) { final float scale = context.getResources().getDisplayMetrics().density; return (int) (dpValue * scale + 0.5f); }
把view的视图转成bitmap:
public static Bitmap getBitmapFromView(View view) { Bitmap bitmap = null; try { int width = view.getWidth(); int height = view.getHeight(); if (width != 0 && height != 0) { bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); view.layout(0, 0, width, height); view.draw(canvas); } } catch (Exception e) { bitmap = null; LogUtil.d("", e.getMessage()); } return bitmap; }