使用LayoutInflater自定义View的疑惑

网上搜了一下自定义控件,发现使用LayoutInflater来做很简单,步骤都是

1.定义一个xml

2.定义一个类,使用xml,可以控制xml中的内容,这个类就是自定义的控件

定义了一个xml名为feng_tab_item.xml如下:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
    <ImageView
    android:id="@+id/image"
    android:layout_width="match_parent"
    android:scaleType="centerInside"
    android:layout_height="@dimen/tabbar_image_height"
    android:contentDescription="@string/image_contentDescription" />
    <TextView 
    android:id="@+id/text"
    android:layout_below="@id/image"
    android:layout_width="match_parent"
    android:gravity="center"
    android:layout_height="18dp" 
    android:textSize="@dimen/tabbar_text_size"
    android:textColor="@color/info_cell_text" />
</RelativeLayout>


定义了一个类如下:

public class FengTabItem extends RelativeLayout
{
	

	public ImageView imageView;
	public TextView textView;
	
	public FengTabItem(Context context) 
	{
		super(context);
		LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		layoutInflater.inflate(R.layout.feng_tab_item, this);
	<span style="white-space:pre">	</span>//此处有问题
<span style="white-space:pre">		</span>int i = getChildCount();
		if (i == 1)
		{
			View view = getChildAt(0);
			if (view instanceof RelativeLayout)
			{
				Log.v("root", "aaaa");
			}
		}
		initViews();
	}
	
	public FengTabItem(Context context, AttributeSet attrs) 
	{
		super(context, attrs);
		LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		layoutInflater.inflate(R.layout.feng_tab_item, this);
		initViews();
	}
	
	void initViews()
	{
		imageView = (ImageView)findViewById(R.id.image);
		textView = (TextView)findViewById(R.id.text);
	}
	
	public void setDrawable(Drawable drawable)
	{
		if(drawable != null)
		{
			imageView.setImageDrawable(drawable);
		}
	}
	
	public void setText(String text)
	{
		if (text != null)
		{
			textView.setText(text);
		}
	}
	
}

问题就出在
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
layoutInflater.inflate(R.layout.feng_tab_item, this);
类本身就是一个RelativeLayout,使用layoutInflater.inflate(R.layout.feng_tab_item, this);xml中也是含有一个RelativeLayout的,检查<
layoutInflater.inflate(R.layout.feng_tab_item, this);之后,自身的child view,只有一个,是RelativeLayout,此时的视图结构就是
RelativeLayout-
<span style="white-space:pre">	</span>RelativeLayout-
<span style="white-space:pre">		</span>ImageView
<span style="white-space:pre">		</span>TextView
这多余了一个RelativeLayout吧?不知道理解是不是正确的?

 
 




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值