- 实例——移动、放大图片
package com.example.a91920.text;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
private FrameLayout root;
private ImageView lv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
root= (FrameLayout) findViewById(R.id.container);
lv= (ImageView) findViewById(R.id.lv);
root.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()){
case MotionEvent.ACTION_DOWN:
System.out.println("action down");
break;
case MotionEvent.ACTION_MOVE:
System.out.println("action move");
System.out.println(String.format("x:%f,y:%f",event.getX(),event.getY()));
//利用getLayoutParams()方法,获取控件的LayoutParams
FrameLayout.LayoutParams lp= (FrameLayout.LayoutParams) lv.getLayoutParams();
lp.leftMargin= (int) event.getX();
lp.topMargin= (int) event.getY();
//将修改好的layoutParams设置为该控件的layoutParams
lv.setLayoutParams(lp);
break;
case MotionEvent.ACTION_UP:
System.out.println("action up");
break;
}
return true;
}
});
}
}
布局文件
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:id="@+id/container"
>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/nice"
android:id="@+id/lv"
/>
</FrameLayout>