前言
最近鸿蒙OS要出了,所以特别想学习一下Android应用的开发(就是想学移动端开发)。
网上没什么靠谱的视频,所以我买了书看,看的是《第一行代码》第二版,Android Studio版本是3.4。
不多说了,前面都是废话,博客主要是我的笔记和我个人理解。
1.新建一个Layout,取名title,是xml文件
2.输入代码:(//是注释,实际上别这样在xml里写注释,我只是方便自己看)
<?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="wrap_content" //这里我没有设定orientation,所以默认是horizontal,所有控件横向排列
android:background="@drawable/layout"> //设置background,"@drawable/layout"是Project模式下,drawable文件夹下的layout.jpg
<Button
android:id="@+id/title_back"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center" //这里和layout_grivaty不一样,gravity只是文字在控件上的居中
android:layout_margin="5dp"
android:background="@drawable/button1"
android:text="Back"
android:textColor="#0ff" />
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:id="@+id/title_text"
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:gravity="center"
android:layout_margin="5dp"
android:background="@drawable/button2"
android:text="Edit" />
</LinearLayout>
效果如下(随便找的图拼起来的):
然后新增一个JavaClass,别告诉我这都不会了
取名:TitleLayout
代码如下:
public class TitleLayout extends LinearLayout {
public TitleLayout(Context context, AttributeSet attrs)
{
super(context,attrs);
//inflate载入两个参数,第一个是布局文件的id,第二个是加载好的布局再添加一个父布局
LayoutInflater.from(context).inflate(R.layout.title,this);
}
}
然后在你想加入的活动的xml文件里加入
//这就引入刚才的TitleLayout的JavaClass了
//TitleLayout里构造函数会inflate界面,inflate里已经指定了布局文件的id,所以,直接在xml引入后,界面上就可以把这个布局当UI渲染出来了
<com.example.myapplication.TitleLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
</com.example.myapplication.TitleLayout>
现在,可以运行看看了。
(当然也有在xml里直接include的方法,这里不赘述了)
至于事件响应,就和正常的一样了,我也不想赘述了。直接在TitleLayout这个JavaClass里加就好了。这样,所有引用这个自定义UI的都会响应你注册的事件。
比如:
Button titleback = (Button)findViewById(R.id.title_back);
titleback.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
((Activity)getContext()).finish();
}
});
//点击左边那个按钮就会退出程序(其实是销毁当前的活动)