组合控件的用法:
第一步:新建一个布局文件,在布局文件中放置好相应的控件,代码如下所示。
代码出处:http://blog.csdn.net/guolin_blog/article/details/17357967
- <?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="50dp"
- android:background="#ffcb05" >
- <Button
- android:id="@+id/button_left"
- android:layout_width="60dp"
- android:layout_height="40dp"
- android:layout_centerVertical="true"
- android:layout_marginLeft="5dp"
- android:background="@drawable/back_button"
- android:text="Back"
- android:textColor="#fff" />
- <TextView
- android:id="@+id/title_text"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_centerInParent="true"
- android:text="This is Title"
第二步:创建一个类继承自FrameLayout,在类的构造函数中用了LayoutInflater的inflate()方法来加载刚刚定义的xml布局文件。关于LayoutInfalter的原理分析可以参考:Android LayoutInflater原理分析,带你一步步深入了解View(一)
参考代码:
代码出处:http://blog.csdn.net/guolin_blog/article/details/17357967
- public class TitleView extends FrameLayout {
- private Button leftButton;
- private TextView titleText;
- public TitleView(Context context, AttributeSet attrs) {
- super(context, attrs);
- LayoutInflater.from(context).inflate(R.layout.title, this);
- titleText = (TextView) findViewById(R.id.title_text);
- leftButton = (Button) findViewById(R.id.button_left);
- leftButton.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View v) {
- ((Activity) getContext()).finish();
- }
- });
- }
- public void setTitleText(String text) {
- titleText.setText(text);
- }
- public void setLeftButtonText(String text) {
- leftButton.setText(text);
- }
- public void setLeftButtonListener(OnClickListener l) {
- leftButton.setOnClickListener(l);
- }
- }
第三步:在布局文件中引用自定义的View文件
代码出处:http://blog.csdn.net/guolin_blog/article/details/17357967
[html] view plaincopy
- <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools"
- android:layout_width="match_parent"
- android:layout_height="match_parent" >
- <com.example.customview.TitleView
- android:id="@+id/title_view"
- android:layout_width="match_parent"
- android:layout_height="wrap_content" >
- </com.example.customview.TitleView>
- </RelativeLayout>
这样就成功将一个标题栏控件引入到布局文件中了,运行一下程序,效果如下图所示: