[Andriod]自定义控件一

本文讲述的自定义的组合控件,实现类似于iPhone的导航栏效果,在导航栏左侧有一个返回按钮,中间是界面的标题,右边是点击的按钮。

(1)第一种方法:
1、新建title.xml布局

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#bbb" >

    <Button
        android:id="@+id/title_back"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_margin="5dip"
        android:background="#fff"
        android:text="Back"
        android:textColor="#ccc" />

    <TextView
        android:id="@+id/title_text"
        android:layout_width="0dip"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_weight="1"
        android:gravity="center"
        android:text="Title Text"
        android:textColor="#ccc"
        android:textSize="24sp" />

    <Button
        android:id="@+id/title_edit"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_margin="5dip"
        android:background="#fff"
        android:text="Edit"
        android:textColor="#ccc" />

</LinearLayout>

2、在main_activity.xml中,通过标记来包含title布局。

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

(2)第二种方法
1、新建自定义控件类:TitleLayout,继承自LinearLayout

package com.example.customview;

import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.widget.LinearLayout;

/**
 * 自定义的控件
 * @author w8
 *
 */
public class TitleLayout extends LinearLayout {
    public TitleLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        // TODO Auto-generated constructor stub

        LayoutInflater.from(context).inflate(R.layout.title, this);
    }
}

在TitleLayout构造方法中,我们通过LayoutInflater来动态加载title布局。

2、在activity_main.xml中修改布局文件,注意需要指定完整的控件类名。

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <!-- 加载自定义的控件,跟普通控件相比,需要指明完整的类名 -->
    <com.example.customview.TitleLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </com.example.customview.TitleLayout>

</LinearLayout>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值