首页 > 移动平台 > 详细

Android中创建自定义控件

时间:2019-03-22 21:20:24      阅读:159      评论:0      收藏:0      [点我收藏+]

1.创建一个TitleLayout继承LinearLayout: 

//创建自定义控件
public class TitleLayout extends LinearLayout {

private final Button titleBack;
private final Button titleEdit;

public TitleLayout(Context context, AttributeSet attrs) {
super(context, attrs);
//通过LayoutInflater的from方法可以创建出一个LayoutInflater对象,然后调用inflate()方法可以动态加载布局文件

LayoutInflater.from(context).inflate(R.layout.title,this);
titleBack = (Button) findViewById(R.id.title_back);
titleEdit = (Button) findViewById(R.id.title_edit);
titleBack.setOnClickListener(new View.OnClickListener(){

@Override
public void onClick(View view) {
((Activity)getContext()).finish();
}
});
titleEdit.setOnClickListener(new View.OnClickListener(){

@Override
public void onClick(View view) {
Toast.makeText(getContext(), "You clicked Edit button", Toast.LENGTH_SHORT).show();
}
});
}
}

2.在activity_main.xml中添加这个自定义控件:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.itheima.album.uicustomviews.MainActivity">
<!--<include layout="@layout/title"/>-->
<com.itheima.album.uicustomviews.TitleLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>

Android中创建自定义控件

原文:https://www.cnblogs.com/peifengyang/p/10580827.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!