第一种是需要写一个XML,然后在自定义代码中获取控件
1
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="200dp">
<android.support.v4.view.ViewPager
android:id="@+id/banner_viewPager"
android:layout_width="match_parent"
android:layout_height="200dp"/>
<LinearLayout
android:layout_alignParentEnd="true"
android:visibility="visible"
android:layout_marginEnd="10dp"
android:layout_marginBottom="10dp"
android:orientation="horizontal"
android:layout_alignBottom="@id/banner_viewPager"
android:id="@+id/banner_points"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></LinearLayout>
</RelativeLayout>
在上面的布局代码中显示了要获取viewPager和LinearLayout
2 接下来在自定义View的构造方法中获取layout,并绑定控件
下面的例子是用buttterKnife,使用findViewById也是可以的
@BindView(R.id.layout_banner_viewpager)
ViewPager viewPager;
@BindView(R.id.layout_banner_points_group)
LinearLayout points;
public BannerView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
LayoutInflater.from(getContext()).inflate(R.layout.layout_custom_banner, this, true);
ButterKnife.bind(this);
imageViewList = new ArrayList<>();
}
第二种方法 :在自定义View中直接写需要的控件实例
以下是用korlin编写的
viewPager=ViewPager(context) val params=RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT) viewPager.layoutParams=params tv = TextView(context) val dotParams=LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT) with(dotParams){ addRule(RelativeLayout.ALIGN_PARENT_BOTTOM) setMargins(0,0,0,ScreenUtil.dip2px(10)) } tv.layoutParams=dotParams tv.gravity=Gravity.CENTER_HORIZONTAL //自己写的 this.addView(viewPager) this.addView(tv)
比较两种方法,
第一种更直观,能直接看到获取控件的位置和大小,缺点是需要写一个布局文件,之后还要在构造方法中获取控件id,
第二种少写了一个布局,还需要对控件位置和大小有把握才好写,但是优点是可以少写一个XML,需要改动的时候就不用在特意去XML中改了