40 likes | 52 Views
設定按鈕置中與正方形. 建國科技大學 資管系 饒瑞佶 2013/4/23. center.xml. < RelativeLayout xmlns:android = "http://schemas.android.com/apk/res/android" android:layout_width = "fill_parent" android:layout_height = "fill_parent" android:id = "@+id/rootlinearlayout" > " < Button android:id = "@+id/button1"
E N D
設定按鈕置中與正方形 建國科技大學 資管系 饒瑞佶 2013/4/23
center.xml <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:id="@+id/rootlinearlayout">" <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button" /> </RelativeLayout>
center.java @Override protectedvoid onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.center); // 取得螢幕解析度 DisplayMetrics dm = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(dm); // 螢幕寬 int width = dm.widthPixels; //螢幕高 int height = dm.heightPixels; // 取得UI xml上的button Button bt1=(Button)findViewById(R.id.button1); // 重設layout RelativeLayout.LayoutParams rel_btn = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); //設定位置置中 rel_btn.leftMargin = (width-50)/2; //距離左邊 rel_btn.topMargin = (height-50)/2; //距離上方 //設定大小,這裡設定一樣就變成正方形 rel_btn.width = 50; rel_btn.height = 50; // 重新把設定指定給button bt1.setLayoutParams(rel_btn); }