---
title: "好奇怪啊！TextView中setWidth方法不起作用"
author: "Qaohao"
date: "2009-12-09T12:10:54Z"
tags: []
categories: ["移动开发"]
slug: "textview-setwidth"
draft: false
lastmod: "2010-06-13T09:40:16Z"
id: 544637
url: "https://qaohao.iteye.com/blog/544637"
---

今天遇到一个很奇怪的问题，我想在layout加载完以后重新再指定一些UI部件的尺寸。在指定TextView时遇到了一些奇怪的问题。

   竟然调用TextView部件的setWidth不起作用，可是文档中明明告诉我们是可以的。

   ![](http://dl.iteye.com/upload/attachment/177843/c37f64ae-28bf-3d0c-8076-31fca0723388.bmp)

   不过通过调用TextView部件上面的getLayoutParams().width来设定，结果行了。类似地setHeight方法也应该不好使，同样地使用getLayoutParams().height去设定就可以。
  
   andoird中指定View的尺寸一般都是通过LayoutParams来设定的，但TextView这个部件中扩展了setWidth、setHeight等方法，我觉得应该是出于这类部件的特殊性吧，所以才提供了这样可以直接设定TextView
尺寸的方法，方便开发者使用。但是为什么就不起作用了，我自己还怀疑过是不是和自己使用的时机有关系，我所有的情况都大概试了一遍，都不好用。可是文档上明明这么写道（以setWidth为例）：

> Makes the TextView exactly this many pixels wide. You could do the same thing by specifying this number in the LayoutParams.


   我理解这句话的意思是，可以设定TextView具体有多少像素宽，你也能通过指定LayoutParams中的数作同样的事情。

   好奇怪啊！