代碼中進行RelativeLayout佈局的修改添加

android用java爲編程語言,很多地方都很相似,界面這塊也很像。我們都知道java畫界面是一行一行代碼去添加界面的控件的,所以那是一件讓人崩潰的事。Android完美解決了這一問題,Android的界面佈局是通過xml文件配置的,加上強大的ide畫界面就非常方便了。但xml佈局侷限就是不能動態修改,所以還是需要像java那樣在代碼中動態添加view。

本人也是新手一個,沒有研究全部佈局,只簡單寫點RelativeLayout的動態佈局,有錯誤及不足,歡迎大家評論指出。


首先,需要獲得RelativeLayout這個對象,可以在xml中給其id,在onCreate中加載佈局後用下面語句獲得。

rootView=(RelativeLayout) findViewById(R.id.rootView);

需要添加的view可以代碼裏new一個,也可以加載佈局xml文件,我是使用xml文件定義了一個LinearLayout,代碼如下


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >

    <Button
        android:id="@+id/selectAll"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="全選" />

    <Button
        android:id="@+id/del_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="刪除" />

    <Button
        android:id="@+id/cancel_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="取消" />

</LinearLayout>

在java代碼中加載這個佈局文件,代碼如下

LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
openView=(LinearLayout) inflater.inflate(R.layout.delmenu_layout, null);
添加到RelativeLayout前還需要設置這個添加進去的view的佈局屬性,需要用到LayoutParams類,但這個類針對不同佈局,需要引入不同的佈局類下的這個類,本例中是在RelativLayout中,就需要RelativeLayout.LayoutParams,建議都這樣寫,不要只寫LayoutParams,有多種佈局絕對會暈死。

RelativeLayout.LayoutParams lp=new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,RelativeLayout.LayoutParams.WRAP_CONTENT);//兩個參數分別是layout_width,layout_height
lp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);//這個就是添加其他屬性的,這個是在父元素的底部。
addRule方法還有個兩個參數的,用於RelativeLayout中相對於某個控件的屬性,如android:layout_alignBottom="@+id/listView1"

可以寫成

lp.addRule(RelativeLayout.ALIGN_BOTTOM,R.id.listView1);

兩者效果一樣,後面那個參數也可以是RelativeLayout.TRUE(-1)和0,如android:layout_alignParentBottom="true"

lp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM,RelativeLayout.TRUE);

最後,添加新的view到RelativeLayout中,

rootView.addView(openView,lp);

補一個刪除的方法

rootView.removeView(menuView);

寫的比較簡單,權當筆記了。歡迎大家指出不足和錯誤。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章