自学安卓复习基础_之八(关于重写页面布局,引用自定义页面布局)

来源:互联网 发布:国产好电影 知乎 编辑:程序博客网 时间:2024/05/24 15:43

在做项目中,我们经常会复用一些相同的页面布局,为了避免过多的代码重复,我们把这些页面提取出来,有两种方式去实现页面重用
方式一:在layout页面中包含另外一个页面

    <include layout="@layout/top" />
方式二:这个方法会比较好,如果包含的页面有点击效果以及其他内容操作的话,可以避免很多代码重复步骤一:创建好重用的代码layout布局页面 top.xml(页面中就两个点击按钮分别是btn1,btn2)步骤三:最主要的步骤,创建TopLayout继承LinearLayout,让它成为我们自定义控件
public class TopLayout extends LinearLayout{    //重写了LinearLayout带有两个参数的构造函数    public Top(Context context, AttributeSet attrs) {        super(context, attrs);        //加载top页面        LayoutInflater.from(context).inflate(R.layout.top, this);        Button btn=(Button) findViewById(R.id.btnOK);        Button btn2=(Button) findViewById(R.id.btnCANCLE);        btn.setOnClickListener(new OnClickListener() {            @Override            public void onClick(View v) {                // TODO Auto-generated method stub                Toast.makeText(getContext(), "点击了OK按钮", Toast.LENGTH_SHORT).show();            }        });        btn2.setOnClickListener(new OnClickListener() {            @Override            public void onClick(View v) {                // TODO Auto-generated method stub                Toast.makeText(getContext(), "点击了CANCLE按钮", Toast.LENGTH_SHORT).show();                //点击btnOK销毁当前的活动                ((Activity)getActivity()).finish();            }        });    }}
步骤四:页面引用自定义控件
    //[com.activity.TopLayout]是TopLayout所在位置全名称 <com.activity.TopLayout        android:layout_width="match_parent"        android:layout_height="wrap_content" >    </com.activity.Top>

这样就成功啦!

0 0
原创粉丝点击