Android 提供多種 View 的 (X, Y) 軸位置設定方式,
如: setLayoutParams
如: setLeft / setTop
如: setX / setY
也提供多種取得 (X, Y) 軸位置的方式,
如: getLeft / getTop
如: getX / getY
之間的差異性, 可以參考下面的範例 :
Layout XML :
XML 內容
<?xml version="1.0" encoding="utf-8"?> <AbsoluteLayout 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/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="我現在位置" /> </AbsoluteLayout>
Main 主程式 :
程式碼
public class TomKuoTest extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView( R.layout.main_test ); setTitle("getX/getY 與 getLeft/getTop 差異"); TextView tv = (TextView)findViewById(R.id.textView); Log.i("test", "===== TextView 尚未變更位置 ====="); Log.i("test", "getX() / getY() : " + tv.getX() + " / " + tv.getY()); Log.i("test", "getLeft() / getTop() : " + tv.getLeft() + " / " + tv.getTop()); Log.i("test", "===== TextView 透過 setLayoutParams 變更位置 ====="); tv.setLayoutParams( new AbsoluteLayout.LayoutParams( LayoutParams.WRAP_CONTENT , LayoutParams.WRAP_CONTENT , 200 , 100 ) ); Log.i("test", "getX() / getY() : " + tv.getX() + " / " + tv.getY()); Log.i("test", "getLeft() / getTop() : " + tv.getLeft() + " / " + tv.getTop()); tv.setLeft(300); tv.setTop(150); Log.i("test", "===== TextView 透過 setLeft / setTop 變更位置 ====="); Log.i("test", "getX() / getY() : " + tv.getX() + " / " + tv.getY()); Log.i("test", "getLeft() / getTop() : " + tv.getLeft() + " / " + tv.getTop()); tv.setX(500); tv.setY(300); Log.i("test", "===== TextView 透過 setX / setY 變更位置 ====="); Log.i("test", "getX() / getY() : " + tv.getX() + " / " + tv.getY()); Log.i("test", "getLeft() / getTop() : " + tv.getLeft() + " / " + tv.getTop()); // 不在同一個程序中取得 View 長寬 new Handler().postDelayed( new Runnable() { @Override public void run() { TextView tv = (TextView)findViewById(R.id.textView); Log.i("test", "Runnable 內 getX() / getY() : " + tv.getX() + " / " + tv.getY()); Log.i("test", "Runnable 內 getLeft() / getTop() : " + tv.getLeft() + " / " + tv.getTop()); } }, 100 ); } }
範例結果, 如下 :