簡體   English   中英

如何動態添加視圖到LinearLayout?

[英]How to add a View Dynamically to a LinearLayout?

有沒有辦法在Android中動態添加圖像並將其放置到線性布局中? 在php中,我只能回顯圖像標簽並使用css對其進行定位,但不確定如何在android中解決此問題,因為xml似乎是非常嚴格的預定義。

您可以通過調用ViewGroup.addView(View)方法將視圖添加到任何ViewGroup。 但是,這是添加視圖的一種模糊方式。 最好是首先為給定的布局創建一個LayoutParams (考慮到視圖),這將允許您更緊密地控制視圖及其與父視圖的關系。

這是將所有內容捆綁在一起的示例:

class MyActivity extends Activity {
    @Override public void onCreate(Bundle icicle) {
        super.onCreate(icicle)

        LinearLayout ll = new LinearLayout(this);
        ll.setOrientation(LinearLayout.VERTICAL);
        // Create 5 view to take up a small amount of space.

        View tmp = null;

        for (int i = 0; i < 5; i++) {
            tmp = new View(this);
            ll.addView(tmpnew LinearLayout.LayoutParams(
                50, // Width
                50);    // Height
            // Either or both the width and height may be ViewGroup.
            // (WRAP_CONTENT || FILL_PARENT || MATCH_PARENT)
        }

        setContentView(ll);
    }
}

這是將視圖動態添加到LinearLayout的方式。 但是,由於LinearLayout的結構和設計,實際上並沒有太多的定位方式。 將LinearLayout視為一個在一個方向上充滿視圖的數組,您唯一可以做的就是更改它們在數組中的位置。 如果您想更好地控制View,建議您使用RelativeLayout。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM