码迷,mamicode.com
首页 > 其他好文 > 详细

自定义控件

时间:2017-04-16 21:34:15      阅读:162      评论:0      收藏:0      [点我收藏+]

标签:near   .sh   居中   version   自定义控件   attrs   back   代码   title   


一.重要知识点

android:background //可以指定图片和颜色
getContext(),获取当前对象所在的Context

xml布局文件转为View对象:
LayoutInflater.from(context).inflate(R.layout.menu, this);

在xml不居中加载另一个xml布局:
<include layout="@layout/menu" />

二.自定义控件:

1.xml代码,menu.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="50dp"
android:orientation="horizontal"
android:background="#D16B07">

<Button
android:text="返回"
android:layout_width="100dp"
android:layout_height="50dp"
android:layout_weight="1"
android:background="@drawable/btn"
android:id="@+id/title_back"
/>

<TextView
android:layout_width="100dp"
android:layout_height="50dp"
android:layout_weight="1"
android:text="标题"
android:gravity="center"/>

<Button
android:text="编辑"
android:layout_width="100dp"
android:layout_height="50dp"
android:layout_weight="1"
android:background="@drawable/btn"
android:id="@+id/title_edit"
/>
</LinearLayout>


2.java代码,Menu.java:
public class Menu extends LinearLayout {

public Menu(Context context, AttributeSet attrs) {
super(context, attrs);
LayoutInflater.from(context).inflate(R.layout.menu, this);

Button back,edit;
back = (Button)findViewById(R.id.title_back);
edit = (Button)findViewById(R.id.title_edit);

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

edit.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getContext(), "编辑", Toast.LENGTH_LONG).show();
}
});
}
}


3.控件引用
<com.example.packname.Menu
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
</com.example.packname.Menu>

 

自定义控件

标签:near   .sh   居中   version   自定义控件   attrs   back   代码   title   

原文地址:http://www.cnblogs.com/itfenqing/p/6719796.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!