书小宅之android开发——自定义控件

顶部标题栏

title.xml中完成标题栏布局,可复用

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
	android:layout_width="match_parent"
	android:layout_height="wrap_content"
	android:background="@drawable/title_bg" >
	
	<Button
		android:id="@+id/title_back"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:layout_gravity="center"
		android:layout_margin="5dp"
		android:background="@drawable/back_bg"
		android:text="Back"
		android:textColor="#fff" />
	
	<TextView
		android:id="@+id/title_text"
		android:layout_width="0dp"
		android:layout_height="wrap_content"
		android:layout_gravity="center"
		android:layout_weight="1"
		android:gravity="center"
		android:text="Title Text"
		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="5dp"
		android:background="@drawable/edit_bg"
		android:text="Edit"
		android:textColor="#fff" />	
</LinearLayout>	

activity_main.xml中用include引入标题栏布局(避免重复编码)

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

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

在MainActivity中将系统自带的标题栏隐藏掉

public class MainActivity extends AppcompatActivity{
	@Override
	protected void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstancedState);
		setContentView(R.layout.activity_main);
		//获得ActionBar的实例
		ActionBar actionBar=getSupportActionBar();
		if(actionBar != null){
			actionBar.hide();
		}
	}
}

自定义控件

如每个活动都需要重新注册一遍按钮的点击事件时,用自定义控件来实现。

public class TitleLayout extends LinearLayout{
//重写构造函数,引用TitleLayout就会调用这个构造函数
	public TitleLayout(Contenxt context,AttributeSet attrs){
		super(context,attrs);
		//对标题栏进行动态加载
		LayoutInflater.from(context).inflate(R.layout.title,this);

		//得到按钮实例
		Button titleBack=(Button)findViewById(R.id.title_back);
		Button titleEdit=(Button)findViewById(R.id.title_edit);
		titleBack.setOnClickListener(new onClickListener(){
			@Override
			public void onClick(View v){
				((Activity)getContext()).finish();
			}
		});		
		titleEdit.setOnClickListener(new onClickListener(){
			@Override
			public void onClick(View v){
				Toast.makeText(getContext(),"You clicked Edit button",Toast.LENGTH_SHORT).show();
			}
		});
	}
}

在添加自定义控件的时候我们需要指明控件的完整类名,包名不可以省略。
activity_main

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

	<com.example.uicustomviews.TitleLayout
		android:layout_width="match_parent"
		android:layout_height="wrap_content" />
</LinearLayout>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值