您的位置:首页 > 编程语言

第一行安卓代码——创建自定义控件3.4

2017-02-14 18:40 381 查看
有时候我们会觉得系统提供的控件不能满足我们的需求。这个时候我们可以自定义控件来使用。

下面我们举个引入布局的例子。

新建title.xml

LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/title_back"
android:layout_width="wrap_content"
android:layout_height="wrap_content"

android:layout_margin="5dp"
android:text="Back"
android:textColor="#fff"/>
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"

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_margin="5dp"
android:text="Edit"
android:textColor="#fff"/>
</LinearLayout


在activity_main.xml中加一行代码

<include layout = "@layout/title"/>


然后在MainActivity中将系统自带的标题栏隐藏掉

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActionBar actionBar = getSupportActionBar();
if( actionBar != null) {
actionBar.hide();
}
}


结果如图



现在已经解决了重复编写布局代码的问题,但是这些控件不能响应事件,怎么办呢?

使用自定义控件的方式来解决

新建TitleLayout

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


在布局文件中添加这个自定义控件

<com.example.hms.a34.TitleLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"></com.example.hms.a34.TitleLayout>


ok,这样的话,每当我们在一个布局中引入TitleLayout时, 返回按钮和编辑按钮的点击事件就都已经自动实现好了,这就省去了许多编写重复代码的工作。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android 控件 布局