Toolbar自定义及自定义控件类的三个构造函数解析

xiaoxiao2021-02-28  92

在Android开发过程中,往往需要使用toolbar作为标题栏。根据不同情况,需要使用不同的toolbar,这个时候就需要我们来自定义toolbar了。 自定义控件中的一种常用方法是new一个类继承你要自定义的控件类,然后就使用你的类名代替原控件。 public class MToobar extends Toolbar{ private View view=null; private Button bumen; public MToobar(Context context) { super(context);Log.d("Dddddd","tttttt1"); } public MToobar(Context context, AttributeSet attrs) { super(context, attrs);Log.d("Dddddd","tttttt2"); } public MToobar(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); Log.d("Dddddd","tttttt3"); } values里面要加一个attrs.xml,里面用来写自定义控件名及属性 <?xml version="1.0" encoding="utf-8"?> <resources> <declare-styleable name="MToobar"> <!--此处写自定义属性--> </declare-styleable> </resources> 然后写好自定义的布局 <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="match_parent"> <Button android:id="@+id/bumen" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="top|left" android:drawableLeft="@drawable/left" android:background="#00000000" android:text="按钮" android:textSize="18sp"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="top" android:layout_centerHorizontal="true" android:text="文字" android:textSize="16sp"/> </RelativeLayout> 自定义类的构造函数中里面引用这个布局。(具体哪个构造函数,下面解释) if(view==null){ view= LayoutInflater.from(getContext()).inflate(R.layout.toobar_content,null); bumen=(Button)view.findViewById(R.id.bumen); ViewGroup.LayoutParams layoutParams=new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.CENTER_HORIZONTAL); addView(view,layoutParams); } 自定义就完成了。然后就可以使用自定义的这个控件类了。 <com.example.shixun.MToobar android:id="@+id/mtoobar" android:layout_width="match_parent" android:layout_height="60dp" android:layout_gravity="top" android:background="#3ef4ff" android:clickable="true"> </com.example.shixun.MToobar> private MToobar mToobar=null; mToobar=(MToobar)findViewById(R.id.mtoobar); 到这里还有一个问题没有解决。就是写自定义toolbar类的时候。必须重新构造函数而且还是三个。那么问题是,这三个构造函数分别在什么时候调用呢。下面我来解释一下。 public class MToobar extends Toolbar{     private View view=null;     private Button bumen;     public MToobar(Context context) {         super(context);Log.d("Dddddd","tttttt1");     }     public MToobar(Context context, AttributeSet attrs) {         super(context, attrs);Log.d("Dddddd","tttttt2");     }     public MToobar(Context context, AttributeSet attrs, int defStyleAttr) {         super(context, attrs, defStyleAttr);         Log.d("Dddddd","tttttt3");     } 第一个构造函数是在你new一个对象的时候调用, 第二个构造函数是在你在xml文件里面声明这个控件时调用,(本例就是调用了第二个) 第三个系统不会自动调用,需要在自己的构造函数中主动调用。
转载请注明原文地址: https://www.6miu.com/read-56823.html

最新回复(0)