android学习之创建自定义控件(续)

前面一篇使用到了自定义控件视图,通过include方法引用控件,实现了基本的自定义控件,但是对于自定义控件的事件功能实现是建立在单个活动中的,假设有多个子活动需要使用自定义控件,就意味着要分别在多个子活动中重复实现自定义的控件功能,显然这是不被推荐的,这里通过继承实现自定义控件类来解决上面的问题


大部分控件都是单独以layout存在,这里以LinearLayout为例:

视图部分:


<?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="match_parent"
    android:orientation="vertical" >
        <com.example.menu.TitleLayout android:layout_width="fill_parent" android:layout_height="wrap_content"></com.example.menu.TitleLayout>
    
        <TextView 
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:textSize="16sp"
            android:textStyle="normal"
            android:layout_marginTop="15dp"
            android:layout_marginLeft="15dp"
            android:layout_marginRight="15dp"
            android:lineSpacingExtra="10dp"
            android:text="中国日报网12月11日电(远达)由中国倡导设立的亚洲基础设施投资银行蓄势待发,不少国家摩拳擦掌、踊跃参与,但也有彷徨徘徊者,有的甚至心生疑忌,视之为对亚太金融格局的挑战,认为亚投行要与世行、亚行分庭抗礼。"
            />
</LinearLayout>


TitleLayout.java


package com.example.menu;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.view.View.OnClickListener;

public class TitleLayout extends LinearLayout implements OnClickListener{
	private Button tittle_back,tittle_index;
	private Context context;
	public TitleLayout(Context context,AttributeSet attrs) {
		super(context,attrs);
		this.context=context;
		LayoutInflater.from(context).inflate(R.layout.title, this);
		initView();
	}
    
	private void initView(){
		tittle_back= (Button) findViewById(R.id.title_back);
		tittle_index=(Button) findViewById(R.id.title_index);
		tittle_back.setOnClickListener(this);
		tittle_index.setOnClickListener(this);
	}
	
	public void onClick(View v) {
		Activity ac=((Activity) context);
		switch (v.getId()) {
		case R.id.title_back:
			ac.finish();
			break;
		case R.id.title_index:
			Intent intent =new Intent(ac,MainActivity.class);
			ac.startActivity(intent);
			break;
		}
		
	}
	
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值