Android 创建自定义控件
来源:互联网 发布:ios屏蔽广告软件 编辑:程序博客网 时间:2024/05/21 01:45
创建自定义控件
- 创建自定义控件
- 创建自定义控件对应的对象
- 创建自定义控件对应的布局件
- 主Activiy中的布局文件中使用 自定义视图activity_mainxml
Android 布局中很多时候系统自带的控件不能满足我们的需求
需要使用自定义控件。
按照以下三个步骤,可以自定义控件:以创建自定义titlebar控件为例
准备工作:创建一个app案例工程,不在赘述。
效果图:
1. 创建自定义控件对应的对象
- 重写构造方法
- 加载布局文件
- 设置监听事件
public class TitleBar extends LinearLayout implements View.OnClickListener { private Button bt_title_back; private Button bt_title_edit; private Button tv_title_text; private Context mycontext;// 在此构造方法中初始化视图 public TitleBar(Context context, @Nullable AttributeSet attrs) { super(context, attrs); this.mycontext = context; LayoutInflater.from(context).inflate(R.layout.diy_title,this); bt_title_back = (Button) findViewById(R.id.bt_title_back); bt_title_edit = (Button) findViewById(R.id.bt_title_edit); bt_title_back.setOnClickListener(this); //通过实现监听接口的方式设置监听 bt_title_edit.setOnClickListener(this); }//监听方法 @Override public void onClick(View v) { if(v==bt_title_back) { Toast.makeText(mycontext, "返回", Toast.LENGTH_SHORT).show(); }else if(v ==bt_title_edit) { Toast.makeText(mycontext, "编辑", Toast.LENGTH_SHORT).show(); } }}
2. 创建自定义控件对应的布局件
布局视图:
布局文件:diy_title.xml
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@android:color/darker_gray" android:orientation="horizontal"> <Button android:id="@+id/bt_title_back" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="0" android:text="返回" /> <TextView android:id="@+id/tv_title_text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:gravity="center" android:text="标题栏" android:textSize="30sp" /> <Button android:id="@+id/bt_title_edit" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="0" android:text="编辑" /></LinearLayout>
3. 主Activiy中的布局文件中使用 自定义视图:activity_main.xml
<com.example.a02diycontroller.ui.TitleBar android:layout_width="match_parent" android:layout_height="wrap_content"></com.example.a02diycontroller.ui.TitleBar>
阅读全文
0 0
- Android创建自定义控件
- 【Android】创建自定义控件
- Android 创建自定义控件
- Android 自定义控件 实现 创建
- 【Android】创建自定义复合控件
- 创建Android自定义组合控件
- 【Android】40、创建自定义控件
- android创建自定义控件步骤
- Android创建自定义复合控件
- android自定义控件的创建和使用
- android自定义控件的创建和使用
- android学习七(创建自定义控件)
- 【Android成长之路】创建自定义控件
- android学习笔记--创建自定义控件
- android自定义view(二)创建复合控件
- android控件——创建自定义控件或布局
- Android自定义控件——创建复合控件
- 自定义控件 创建复合控件
- 被低估的BIRT报表(二):Birt也可以很漂亮
- 从vue文件中抽取出子组件的流程及过程中踩过的坑
- Opencv绘制灰度/彩色图像的直方图及直方图的均衡化实例及源代码
- 蓝牙模块调试笔记
- 51nod 1580 铺管道
- Android 创建自定义控件
- 单例模式之:高效非同步方法实现
- 克隆创建PDB--(1)本地克隆创建PDB
- Add to List 442. Find All Duplicates in an Array(java)
- win7下IIS配置以及域名映射方法
- Python-元类
- codeforces 271A(Beautiful Year) Java
- MongoDB详细介绍
- JDBC的业务逻辑流程和模块开发的原理分析