代码思想来自于《第一行代码:Android》,此文章为做笔记和整理之用。
一、引入布局(引入xml)
有一些布局重复大量,引入布局解决重复编写布局代码的问题。
1.创建一个自定义布局xml
2.在程序中使用该布局
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <include layout="@layout/title1"/> </LinearLayout>
3.最后可以在MainActivity中把标题栏隐藏掉。
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ActionBar actionBar=getSupportActionBar(); if(actionBar!=null){ actionBar.hide(); }
二、引入自定义控件(引入Layout)
布局中有一些控件能够响应事件,而且该控件大量重复
1.在活动中新建控件TitleLayout(准确来说是一整个Layout)
public class TitleLayout extends LinearLayout{ public TitleLayout(Context context, AttributeSet attrs){ super(context,attrs); LayoutInflater.from(context).inflate(R.layout.title,this);}}//动态加载布局文件,R.layout为接下来要进入的布局,this为此布局
2.在布局文件中添加该控件(与普通控件一样,但是要加上包名)
<com.example.uicustomviews.TitleLayout //包名为书中的代码,是否要改成自己的? android:layout_width="match_parent" android:layout_height="wrap_context"/>
3.尝试为控件中的按钮注册点击事件
public class TitleLayout extends LinearLayout{ public TitleLayout(Context 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(); } }); }
如果需要多个可响应的控件,应该把引入布局和引入自定义控件一起使用。