您的位置:首页 > 移动开发 > Android开发

Android 创建自定义布局

2015-12-18 15:25 579 查看
我们所有的控件都是继承至View类的,而所有的布局都是继承至ViewGroup的,所以我们也可以继承某个view类来实现我们自己的布局或者控件.

引入布局

我们新建一个title.xml的layout文件.

<?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="horizontal" >
<Button
android:id="@+id/btn_back"
android:layout_width="80dp"
android:layout_height="40dp"
android:text="back" />

<TextView
android:layout_width="0dp"
android:layout_height="40dp"
android:layout_weight="1"
android:gravity="center"
android:text="title"
android:textSize="24sp" />

<Button
android:id="@+id/btn_next"
android:layout_width="80dp"
android:layout_height="40dp"
android:text="next" />
</LinearLayout>

然后在mian_activity.xml文件中引用.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
tools:context="com.example.alertdialog.MainActivity" >

<!-- 引用title.xml文件 -->
<include layout="@layout/title"/>
<Button
android:id="@+id/btn"
android:layout_width="match_parent"
android:layout_height="40dp"
/>
</LinearLayout>


创建自定义控件

新建一个titleLayout的class文件,让他继承至LinearLayout类

package com.example.alertdialog;
import android.app.Activity;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;

public class TitleLayout extends LinearLayout{

public TitleLayout(Context context, AttributeSet attrs) {
super(context, attrs);
LayoutInflater.from(context).inflate(R.layout.title, this);
findViewById(R.id.btn_back).setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
((Activity)getContext()).finish();  //获取到当前正在活动的activity,然后finish掉.
}
});
findViewById(R.id.btn_next).setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
Toast.makeText(getContext(), "next", Toast.LENGTH_SHORT).show();
}
});
}
}

然后我们可以在layout文件中字节通过类的路径来进行引用.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
tools:context="com.example.alertdialog.MainActivity" >

<com.example.alertdialog.TitleLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
></com.example.alertdialog.TitleLayout>
<Button
android:id="@+id/btn"
android:layout_width="match_parent"
android:layout_height="40dp"
/>
</LinearLayout>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: