[Android開發] 代碼code設置9.png/9-patch 圖片背景後,此view中的TextView等控件顯示不正常(常見於listview中)

因爲需求的緣故,需要對liview顯示項做黑白相間的處理:

其實就是在函數public View getView(int position, View convertView, ViewGroup parent)

中,加上:

if (position % 2 == 0) {
				convertView.setBackgroundResource(R.drawable.list_gray_9);
			} else {
				convertView.setBackgroundResource(R.drawable.list_white_9);
			}
可是,正如上述代碼可見,我加入的是9-patch圖片,直接導致我的convertView中的內容無法正常顯示了。

這可怎麼辦呢?我在xml中直接設置9-patch給一個layout什麼的,都是正常顯示呀,這個怎麼就出問題了呢?

問題在於以下函數:

public void setBackgroundResource (int resid) Set the background to a given resource. The resource should refer to a Drawable object or 0 to remove the background.


也就是說,其實setBackgroundResource接着調用的應該是:setBackgroundDrawable函數,讓我們看看setBackgroundDrawable的描述:

public void setBackgroundDrawable (Drawable d) Since: API Level 1 Set the background to a given Drawable, or remove the background. If the background has padding, this View's padding is set to the background's padding. However, when a background is removed, this View's padding isn't touched. If setting the padding is desired, please use setPadding(int, int, int, int).Parametersd The Drawable to use as the background, or null to remove the background

也就是說,因爲9-patch有自己的padding,所以convertView自己的padding被覆蓋了!那可咋辦呢?

其實知道這個了就很簡單了,只要在代碼setBackgroundResource之後加上(Remember:一定是這句之後!)一句:

convertView.setPadding(0, 0, 0, 0);

就可以解決問題了~

是不是挺奇怪的,其實很多時候我們有些問題解決不了是因爲不瞭解其內部機制(當然有些時候其內部機制稍顯怪誕),只要瞭解了,便可以應用自如了。

希望各位能從我的文章中找到有用的東西~~~




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章