日本黄色一级经典视频|伊人久久精品视频|亚洲黄色色周成人视频九九九|av免费网址黄色小短片|黄色Av无码亚洲成年人|亚洲1区2区3区无码|真人黄片免费观看|无码一级小说欧美日免费三级|日韩中文字幕91在线看|精品久久久无码中文字幕边打电话

當(dāng)前位置:首頁 > 嵌入式 > 嵌入式軟件
[導(dǎo)讀] 本文主要講述如何動態(tài)給UI界面添加布局和控件,在編程的時候很多時候需要動態(tài)顯示一些內(nèi)容,在動態(tài)添加View的時候,主要使用addView方法。1. addView方法簡介在Android 中

 本文主要講述如何動態(tài)給UI界面添加布局和控件,在編程的時候很多時候需要動態(tài)顯示一些內(nèi)容,在動態(tài)添加View的時候,主要使用addView方法。

1. addView方法簡介

在Android 中,可以利用排版View的 addView 函數(shù),將動態(tài)產(chǎn)生的View 物件加入到排版View 中。

例子如下:

Activity代碼:

public class helloWorld extends Activity {

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView( R.layout.main );

// 取得LinearLayout 物件

LinearLayout ll = (LinearLayout)findViewById(R.id.viewObj);

// 將TextView 加入到LinearLayout 中

TextView tv = new TextView(this);

tv.setText(Hello World);

ll. addView ( tv );

// 將Button 1 加入到LinearLayout 中

Button b1 = new Button(this);

b1.setText(取消);

ll. addView ( b1 );

// 將Button 2 加入到LinearLayout 中

Button b2 = new Button(this);

b2.setText(確定);

ll. addView ( b2 );

// 從LinearLayout 中移除Button 1

ll. removeView ( b1 );

}

}

上述代碼的位置,是垂直順序排列的因為界面代碼Linerlayout的orientation設(shè)置的是vertical的,但是為了美觀,需要設(shè)置添加的View的位置和樣式。在添加View的時候分為兩類來介紹,一種是布局(例如:Linearlayout等),一種是控件(例如:Button,TextView等等。)

2. 動態(tài)添加布局(包括樣式和位置)

下面的例子將介紹如何動態(tài)添加布局,基本內(nèi)容和上面的代碼一致,主要注重如何控制添加的布局的位置。在控制布局的位置的時候使用LayoutParam類來實現(xiàn)。

例子:

界面代碼和上面的界面代碼類似,就不在重復(fù)介紹。

Activity類部分代碼:

RelativeLayout rl = new RelativeLayout(this);

//設(shè)置RelativeLayout布局的寬高

RelativeLayout.LayoutParams relLayoutParams=new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);

this.addView(rl, relLayoutParams);

3. 動態(tài)添加控件

動態(tài)添加控件和添加布局很相似,下述代碼主要注重看控制控件的位置,下面的代碼和第二項添加布局的補充,在新添加的布局里面再添加控件。

界面代碼同樣不在重復(fù)。

Activity類部分代碼:

RelativeLayout rl = new RelativeLayout(this);

//設(shè)置RelativeLayout布局的寬高

RelativeLayout.LayoutParams relLayoutParams=new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);

TextView temp = new TextView(this);

temp .setId(1);

temp.setText(“圖片”);

rl.addView(temp);

TextView tv = new TextView(this);

tv.setText(“文字”);

tv.setId(2);

LayoutParams param1 = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);

param1.addRule(RelativeLayout.BELOW, 1);//此控件在id為1的控件的下邊

rl.addView(tv,param1);

Button update = new Button(this);

update.setText(Button);

LayoutParams param2 = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);

param2.addRule(RelativeLayout.RIGHT_OF, 1);//此控件在id為1的控件的右邊

rl.addView(update,param2);

this.addView(rl, relLayoutParams);

注意:控制位置和樣式的時候,布局和控件使用的方法是一樣的。

本站聲明: 本文章由作者或相關(guān)機構(gòu)授權(quán)發(fā)布,目的在于傳遞更多信息,并不代表本站贊同其觀點,本站亦不保證或承諾內(nèi)容真實性等。需要轉(zhuǎn)載請聯(lián)系該專欄作者,如若文章內(nèi)容侵犯您的權(quán)益,請及時聯(lián)系本站刪除( 郵箱:macysun@21ic.com )。
換一批
延伸閱讀
關(guān)閉