缩放系列(二):所有子控件也随着缩放、手势缩放、多点触控layout

下面是一个功能强大的改造的例子:

可以实现以下需求:

1.两个手指进行缩放布局

2.所有子控件也随着缩放,

3.子控件该有的功能不能丢失(像button有可被点击的功能,缩放后不能丢失该功能)

 运行效果图:


java代码如下

MainActivity.java:

public class MainActivity extends ActionBarActivity {
    private ScaleGestureDetector mScaleGestureDetector = null;
    private View view;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // setContentView(R.layout.test);
        view = View.inflate(this, R.layout.activity_main, null);
        setContentView(view);
        
        mScaleGestureDetector = new ScaleGestureDetector(this,
                new ScaleGestureListener());


    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        // 返回给ScaleGestureDetector来处理
        return mScaleGestureDetector.onTouchEvent(event);
    }

    public class ScaleGestureListener implements
            ScaleGestureDetector.OnScaleGestureListener {

        private float scale;
        private float preScale = 1;// 默认前一次缩放比例为1

        @Override
        public boolean onScale(ScaleGestureDetector detector) {

            float previousSpan = detector.getPreviousSpan();
            float currentSpan = detector.getCurrentSpan();
            if (currentSpan < previousSpan) {
                // 缩小
                // scale = preScale-detector.getScaleFactor()/3;
                scale = preScale - (previousSpan - currentSpan) / 1000;
            } else {
                // 放大
                // scale = preScale+detector.getScaleFactor()/3;
                scale = preScale + (currentSpan - previousSpan) / 1000;
            }

            // 缩放view
            ViewHelper.setScaleX(view, scale );// x方向上缩小
            ViewHelper.setScaleY(view, scale );// y方向上缩小

            return false;
        }

        @Override
        public boolean onScaleBegin(ScaleGestureDetector detector) {
            // 一定要返回true才会进入onScale()这个函数
            return true;
        }

        @Override
        public void onScaleEnd(ScaleGestureDetector detector) {
            preScale = scale;//记录本次缩放比例
        }
    }
}

布局文件(activity_main.xml):




    

    

    

    


 selector_button1.xml:



    
    

selector_button2.xml



    
    

如果想要整个布局能够移动,可以看下面的帖子:

缩放系列(三):一个可以手势缩放、拖拽、旋转的layout

源码地址: https://github.com/Jszgw/ScaleLayout2

你可能感兴趣的:(android)