第一行安卓代码——创建自定义控件3.4
2017-02-14 18:40
381 查看
有时候我们会觉得系统提供的控件不能满足我们的需求。这个时候我们可以自定义控件来使用。
下面我们举个引入布局的例子。
新建title.xml
在activity_main.xml中加一行代码
然后在MainActivity中将系统自带的标题栏隐藏掉
结果如图
现在已经解决了重复编写布局代码的问题,但是这些控件不能响应事件,怎么办呢?
使用自定义控件的方式来解决
新建TitleLayout
在布局文件中添加这个自定义控件
ok,这样的话,每当我们在一个布局中引入TitleLayout时, 返回按钮和编辑按钮的点击事件就都已经自动实现好了,这就省去了许多编写重复代码的工作。
下面我们举个引入布局的例子。
新建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时, 返回按钮和编辑按钮的点击事件就都已经自动实现好了,这就省去了许多编写重复代码的工作。
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- Android IPC进程间通讯机制
- Android Manifest 用法
- [转载]Activity中ConfigChanges属性的用法
- Android之获取手机上的图片和视频缩略图thumbnails
- Android之使用Http协议实现文件上传功能
- Android学习笔记(二九):嵌入浏览器
- android string.xml文件中的整型和string型代替
- i-jetty环境搭配与编译
- android之定时器AlarmManager
- android wifi 无线调试
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- android 代码实现控件之间的间距
- android FragmentPagerAdapter的“标准”配置
- Android"解决"onTouch和onClick的冲突问题
- android:installLocation简析
- android searchView的关闭事件