目标=把helloworld的文字变成可以缩放的。
测试=需要能实体手机,虚拟机似乎不能进行触摸缩放测试。
版本=android 2.3.3,target=android-10
参考了网上例子。
关键点
=============main.xml
<TextView android:id="@+id/text"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="@string/hello" />
=============A1Activity.java
public void onCreate中,加入:
TextView textView = (TextView) findViewById(R.id.text);
textView.setOnTouchListener(this);
加入public boolean onTouch和相关变量
public boolean onTouch中,最后return true;是关键。
关键文件代码
=============main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:id="@+id/text" android:layout_width="fill_parent" android:layout_height="fill_parent" android:text="@string/hello" /> </LinearLayout>
=============A1Activity.java
package com.ex.a1205; import android.app.Activity; import android.os.Bundle; import android.util.FloatMath; import android.util.Log; import android.util.TypedValue; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import android.widget.TextView; public class A1Activity extends Activity implements OnTouchListener { private static final String TAG = "textZoom"; // We can be in one of these 2 states static final int NONE = 0; static final int ZOOM = 1; int mode = NONE; static final int MIN_FONT_SIZE = 20; static final int MAX_FONT_SIZE = 150; float oldDist = 1f; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); TextView textView = (TextView) findViewById(R.id.text); textView.setOnTouchListener(this); } public boolean onTouch(View v, MotionEvent event) { TextView textView = (TextView) findViewById(R.id.text); switch (event.getAction() & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_POINTER_DOWN: oldDist = spacing(event); Log.d(TAG, "oldDist=" + oldDist); if (oldDist > 10f) { mode = ZOOM; } break; case MotionEvent.ACTION_POINTER_UP: mode = NONE; break; case MotionEvent.ACTION_MOVE: if (mode == ZOOM) { float newDist = spacing(event); if (newDist > 10f) { float scale = newDist / oldDist; if (scale > 1) { scale = 1.1f; } else if (scale < 1) { scale = 0.95f; } float currentSize = textView.getTextSize() * scale; if ((currentSize < MAX_FONT_SIZE && currentSize > MIN_FONT_SIZE) || (currentSize >= MAX_FONT_SIZE && scale < 1) || (currentSize <= MIN_FONT_SIZE && scale > 1)) { textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, currentSize); } } } break; } return true; } /** Determine the space between the first two fingers */ private float spacing(MotionEvent event) { float x = event.getX(0) - event.getX(1); float y = event.getY(0) - event.getY(1); return FloatMath.sqrt(x * x + y * y); } }
执行结果
似曾相识