Android 中使用代碼動態布局

來源:互聯網
上載者:User

標籤:getidentifier   android   布局   動態布局   

Android 中使用代碼動態布局


本文介紹在android中使用代碼動態布局,有時候根據不同的需求,比如需要根據伺服器上的條目個數來決定app中頁面配置控制項(顯示個數,表徵圖等)。此處介紹通過java代碼進行動態布局。


一、:


圖片隨便找的,將就將就吧


二、給出xml檔案布局

<?xml version="1.0" encoding="utf-8"?><ScrollView xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:background="@android:color/white" >    <LinearLayout        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:orientation="vertical" >        <!-- 此處標題列可以自訂,因為每一個頁面都有標題,返回,等等 -->        <RelativeLayout            android:id="@+id/layout_titlebar"            android:layout_width="match_parent"            android:layout_height="48dp"            android:layout_marginBottom="20dp"            android:background="#ed4255" >            <TextView                android:id="@+id/text_title"                style="@style/Text.Title"                android:layout_width="match_parent"                android:layout_height="match_parent"                android:gravity="center"                android:text="業務功能介紹" />        </RelativeLayout>        <!-- 子布局由代碼動態產生 -->        <LinearLayout            android:id="@+id/layout_more"            android:layout_width="match_parent"            android:layout_height="match_parent"            android:orientation="vertical"            android:padding="4dp" />    </LinearLayout></ScrollView>


三、子條目xml布局檔案

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="84dp"    android:layout_weight="1.0"    android:clickable="true" >    <ImageView        android:id="@+id/image_icon"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_gravity="center_horizontal"        android:layout_marginTop="16dp"        android:duplicateParentState="true"        android:src="@drawable/ic_department_01_normal" />    <TextView        android:id="@+id/text_title"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_gravity="center_horizontal|bottom"        android:background="@null"        android:layout_marginBottom="6dp"        android:gravity="center"        android:duplicateParentState="true"        android:textColor="@drawable/text_service_color"        android:textSize="14dp" /></FrameLayout>




四、java代碼動態布局

/** * @author gao_chun * */public class MainActivity extends Activity implements OnClickListener{    private ViewGroup mMoreLayout;  //父版面配置容器(動態載入的資源圖片和文字等布局都將添加在其裡面)    /* (non-Javadoc)     * @see app.ui.TitleActivity#onCreate(android.os.Bundle)     */    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        initUI();   //保證啟動方法的唯一性    }    private void initUI() {        setContentView(R.layout.activity_main);        //找到該容器(這裡的控制項為LinearLayout,轉換為ViewGroup是因為ViewGroup是容器的基類)        mMoreLayout = (ViewGroup) findViewById(R.id.layout_more);        //由於文字也是動態產生,使用android中array檔案定義資源檔,並取出        final String[] categories = getResources().getStringArray(R.array.categories);        final int size = categories.length;     //String[]的長度        final int rowCount = size / 3;          //需要布局的行數(每行三個)        /**         * 動態添加布局方法封裝         * 參數 1.父容器    2.資源文字數組  3.從第幾個開始   4.行數         */        fillViews(mMoreLayout, categories, 0, rowCount);    }    private void fillViews(ViewGroup layout, String[] categories, int start, int end) {        // 表格第一條線        View.inflate(this, R.layout.layout_line_horizonal, layout);        for (int i = start; i < end; i++) {            //找到索引,便於根據索引添加圖片檔案和文字            final int firstIndex = i * 3;            final int secondIndex = i * 3 + 1;            final int thirdIndex = i * 3 + 2;            final String firstCategory = categories[firstIndex];            final String secondCategory = categories[secondIndex];            final String thirdCategory = categories[thirdIndex];            //這裡控制的是載入本地圖片,通過應用程式套件命找到 有規則命名的圖片資源檔            //--->因為這裡有兩種效果,一是預設的圖片,二是按下觸發後的圖片和文字            final int firstDrawableNormal = getResources().getIdentifier(String.format("ic_department_%02d_normal",                    firstIndex + 1),"drawable",getApplicationContext().getPackageName());            final int secondDrawableNormal = getResources().getIdentifier(String.format("ic_department_%02d_normal",                    secondIndex + 1),"drawable",getApplicationContext().getPackageName());            final int thirdDrawableNormal = getResources().getIdentifier(String.format("ic_department_%02d_normal",                    thirdIndex + 1),"drawable",getApplicationContext().getPackageName());            final int firstDrawablePressed = getResources().getIdentifier(String.format("ic_department_%02d_pressed",                    firstIndex + 1),"drawable",getApplicationContext().getPackageName());            final int secondDrawablePressed = getResources().getIdentifier(String.format("ic_department_%02d_pressed",                    secondIndex + 1),"drawable",getApplicationContext().getPackageName());            final int thirdDrawablePressed = getResources().getIdentifier(String.format("ic_department_%02d_pressed",                    thirdIndex + 1),"drawable",getApplicationContext().getPackageName());            //這裡是將上面找到的   預設圖片  和  按下時的圖片 放入到  StateListDrawable緩衝中            final StateListDrawable firstDrawable = new StateListDrawable();            firstDrawable.addState(new int[]{android.R.attr.state_pressed}, getResources().getDrawable(firstDrawablePressed));            firstDrawable.addState(new int[]{}, getResources().getDrawable(firstDrawableNormal));            final StateListDrawable secondDrawable = new StateListDrawable();            secondDrawable.addState(new int[]{android.R.attr.state_pressed}, getResources().getDrawable(secondDrawablePressed));            secondDrawable.addState(new int[]{}, getResources().getDrawable(secondDrawableNormal));            final StateListDrawable thirdDrawable = new StateListDrawable();            thirdDrawable.addState(new int[]{android.R.attr.state_pressed}, getResources().getDrawable(thirdDrawablePressed));            thirdDrawable.addState(new int[]{}, getResources().getDrawable(thirdDrawableNormal));            // 父布局            final LinearLayout linearLayout = new LinearLayout(this);            // 第一個子布局            View.inflate(this, R.layout.layout_line_vertical, linearLayout);            View.inflate(this, R.layout.layout_department, linearLayout);            View.inflate(this, R.layout.layout_line_vertical, linearLayout);            // 第二個子布局            View.inflate(this, R.layout.layout_department, linearLayout);            View.inflate(this, R.layout.layout_line_vertical, linearLayout);            // 第三個子布局            View.inflate(this, R.layout.layout_department, linearLayout);            View.inflate(this, R.layout.layout_line_vertical, linearLayout);            LayoutParams layoutParams = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT);            layout.addView(linearLayout, layoutParams);            // 表格最後一條線            View.inflate(this, R.layout.layout_line_horizonal, layout);            //根據索引getChildAt到指定的位置            final View firstView = linearLayout.getChildAt(1);            firstView.setTag(firstCategory);        //設定tag,便於在後面判斷點擊的哪一個            firstView.setOnClickListener(this);     //設定點擊            final TextView firstTextView = (TextView) firstView.findViewById(R.id.text_title);            firstTextView.setText(firstCategory);   //設定文字            final ImageView firstImageView = (ImageView) firstView.findViewById(R.id.image_icon);            firstImageView.setImageDrawable(firstDrawable); //將之前緩衝的圖片設定出來            final View secondView = linearLayout.getChildAt(3);            secondView.setTag(secondCategory);            secondView.setOnClickListener(this);            final TextView secondTextView = (TextView) secondView.findViewById(R.id.text_title);            secondTextView.setText(secondCategory);            final ImageView secondImageView = (ImageView) secondView.findViewById(R.id.image_icon);            secondImageView.setImageDrawable(secondDrawable);            final View thirdView = linearLayout.getChildAt(5);            thirdView.setTag(thirdCategory);            thirdView.setOnClickListener(this);            final TextView thirdTextView = (TextView) thirdView.findViewById(R.id.text_title);            thirdTextView.setText(thirdCategory);            final ImageView thirdImageView = (ImageView) thirdView.findViewById(R.id.image_icon);            thirdImageView.setImageDrawable(thirdDrawable);        }    }    /* (non-Javadoc)     * @see app.ui.TitleActivity#onClick(android.view.View)     */    @Override    public void onClick(View v) {        final Object tag = v.getTag();      //通過之前setTag找到點擊位置        if (tag != null) {            String department = (String) tag;            Toast.makeText(this, department, 0).show();        } // else ignored    }}

在onClick事件中通過布局時設定的Tag找出使用者點擊的是哪一個具體的Layout

註:關於 getResources().getIdentifier 方法可參考:http://blog.csdn.net/gao_chun/article/details/45891383



歡迎下載源碼:http://download.csdn.net/download/gao_chun/8740979



Android 中使用代碼動態布局

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.