Android動態設置控件大小以及設定margin以及padding值

一、概述

在android開發了,我們經常會遇到動態添加控件,或許是TextView或者Button之類的,需要設置控件的大小,margin值或者padding值,注意,一般默認的寬是填充父窗體,高爲包裹內容;

二、實現過程(以TextView爲例)

TextView textView = new TextView(getApplicationContext());
		textView.setBackgroundColor(Color.GRAY);
		textView.setTextColor(Color.WHITE);
		textView.setText("動態設置控件大小");
		
		// 1、設置固定大小
		 LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(200, 100);	 
		// 設置包裹內容或者填充父窗體大小
		 LinearLayout.LayoutParams lp2 = new LinearLayout.LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);	
		//設置padding值
		textView.setPadding(10, 10, 10, 10);
		//設置margin值
		 lp.setMargins(20, 20, 0, 20);
		view.addView(textView,lp);

以上方法經本人親測,絕對不會出錯;

三、以下是錯誤的做法(本人親測)

第一種做法:

LinearLayout.LayoutParams linearParams =(LinearLayout.LayoutParams) textView.getLayoutParams(); //取控件textView當前的佈局參數  
linearParams.height = 20;// 控件的高強制設成20  
  
linearParams.width = 30;// 控件的寬強制設成30   
  
textView.setLayoutParams(linearParams); //使設置好的佈局參數應用到控件</pre>  

第二種做法

	LayoutParams laParams=(LayoutParams)textView.getLayoutParams();
		 laParams.height=200;
		 laParams.width=100;	
		view.addView(textView,laParams);
這兩種方法一般會有空指針異常,我試了很多遍,都會出錯;

四、總結

希望給大家一些幫助,祝工作愉快!

發佈了22 篇原創文章 · 獲贊 39 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章