您的位置:首页 > 其它

自定义布局控件

2015-11-07 17:14 357 查看
本文介绍一种自定义控件的方法,由控件布局和控件代码2部分组成。效果为一个自定义标题栏,由一个按钮、一个文本、一个按钮组成,并定义了各子件的事件。

一、title布局如下

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<Button
android:id="@+id/title_back"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="5dip"
android:text="Back"
android:textColor="#fff" />

<TextView
android:id="@+id/title_text"
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1"
android:gravity="center"
android:text="Title Text"
android:textColor="#fff"
android:textSize="24sp" />

<Button
android:id="@+id/title_edit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="5dip"
android:text="Edit"
android:textColor="#fff" />

</LinearLayout>

二、代码如下。重写构造器,在其中展开布局,找到子控件绑定事件

public class TitleLayout extends LinearLayout {
public TitleLayout(Context context, AttributeSet attrs) {
super(context, attrs);
LayoutInflater.from(context).inflate(R.layout.title, this);
Button titleBack = (Button) findViewById(R.id.title_back);
Button titleEdit = (Button) findViewById(R.id.title_edit);
titleBack.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
((Activity) getContext()).finish();
}
});
titleEdit.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getContext(), "You clicked Edit button",
Toast.LENGTH_SHORT).show();
}
});
}
}

三、活动中引入自定义控件,要使用完整包名

<com.ui.TitleLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
四、自定义控件也可以在主活动中重新定义子控件的属性及事件
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: