网上搜了一下自定义控件,发现使用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吧?不知道理解是不是正确的?