android 开发艺术view笔记

1,073 阅读2分钟

Android动态设置Margin

可以使用LinearLayout.LayoutParams类进行调整

LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) textview.getLayoutParams();
lp.leftMargin = 0;//可以直接改变边界距离
//layoutParams.leftMargin = textview.getLeft()+100;
textview.setLayoutParams(lp);

该方法要在控件已经存在的情况下才可以使用

要是上面的不可以可以用下面这个方法

LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(10,10,10,10);//4个参数按顺序分别是左上右下
textview.setLayoutParams(layoutParams);

弹性滑动

  1. 使用scroller
  2. 通过动画
  3. 使用延时策略

使用scroller

图中的流程为先通过smoothScrollTo设定滑动的参数然后调用invalidate方法对view进行重绘,其中invalidate又会调用computeScroll方法,然后又调用postinvalidate方法进行二次重绘。

通过动画

接下来的代码是让view的内容才100ms内向左移动100像素 ObjectAnimator.ofFloat(targetView,"translationX",0,100).setDuration(100).start()

targetview为控件的对象,translationX为字符串关键字


getAnimatedValue()和getAnimatedFraction()的区别

getAnimatedValue()的返回值是一个Object,表示当仅有一个属性处于动画状态时,由该ValueAnimator计算的当前属性值。 getAnimatedFraction()的返回值是一个float,其值在0.0和1.0之间,其线性度是由插值器决定的(fraction = t / duration ),而animatedValue值是由相关属性值 * fraction所得的。


使用延时策略

核心思想是通过发送一系列的延时消息从而达到一种渐进式的效果,具体来说可以使用Handler或View的postDelayed方法,或者线程的Sleep方法。

循环多次发送信息以及刷新控件的位置

事件分发机制

三个方法

  1. public boolean dispatchTouchEvent(MotionEvent ev)
  2. public boolean onInterceptTouchEvent(MotionEvent event)
  3. public boolean onTouchEvent(MotionEvent event)

这三个方法的联系是,当前若是有点击事件,dispatchTouchEvent会被调用。然后调用onInterceptTouchEvent判断当前是否viewGroup是否拦截事件,若是拦截的话是当前view的onTouchEvent处理,反之传递到子元素中重复当前操作。

Activity对点击事件的分发过程

  1. 当一个点击操作发生时,事件最先传递给当前的Activity
  2. Activity根据dispatchTouchEvent来进行事件分发
  3. Window会将事件传递给decor view(当前页面的底层容器->级setContentView所设置的View的父容器)。decor view可以通过Activity.getWindow().getDecorView()获得。
View v;
v = this.getWindow().getDecorView();
         linearLayout = (LinearLayout)findViewById(R.id.linearlayout);
        ObjectAnimator.ofFloat(v,"translationX",0,100).etDuration(100).start();//该代码可以移动整个页面(非属性绘图)。

通过 ((ViewGroup)getWindow().getDecorView().findViewById(android.R.id.content)).getChildAt(0) 可以获取Activity所设置的View。