今天給大家?guī)淼氖亲远xView歇盼,然后如何設(shè)置他的寬高攘烛,經(jīng)常用自定義view的程序猿肯定都知道我們在給自定義view設(shè)置wrap_content或者match_parent魏滚,view都會占滿全屏,就想如下
以下是方法坟漱,不提供自定義view的布局了鼠次,很簡單,就是繪一個(gè)藍(lán)色的圓
第一種方式(布局修改)
第一種方法也是最簡單的方法芋齿,我們直接給自定義view限制一個(gè)寬高
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.administrator.ceshi.MainActivity">
<com.example.administrator.ceshi.MyView
android:layout_width="200dp"
android:layout_height="200dp"
android:background="@color/colorAccent"/>
</LinearLayout>
效果如下
第二種方式(動態(tài)添加view修改寬高)
隨著我們的技術(shù)不斷提升腥寇,自定義view應(yīng)用的場所也越來越多,如果我們動態(tài)的去添加自定義View呢沟突,就無法限制布局的寬高了花颗,所以我們接下來講解的是第二種用法
為了顯示效果主布局我們什么都不寫
activity_main
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.administrator.ceshi.MainActivity"
android:id="@+id/rl">
</LinearLayout>
MainActivity
普通的動態(tài)添加view是這樣的
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rl = (RelativeLayout) findViewById(R.id.rl);
MyView my=new MyView(this);
my.setBackgroundColor(getResources().getColor(R.color.colorAccent));
rl.addView(my);
}
效果如下
我們只需要在myview再添加一個(gè)寬高的RelativeLayout布局即可
方法如下
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rl = (RelativeLayout) findViewById(R.id.rl);
RelativeLayout.LayoutParams params=new RelativeLayout.LayoutParams(200,200);
MyView my=new MyView(this);
my.setBackgroundColor(getResources().getColor(R.color.colorAccent));
my.setLayoutParams(params);
rl.addView(my);
}
效果
為什么和第一種有區(qū)別呢?原因很簡單惠拭,他們的單位不一樣扩劝,new RelativeLayout.LayoutParams(200,200);
一個(gè)是像素單位庸论,一個(gè)是dp單位
我們把這里的200全部改成400就和上面的一模一樣了
其實(shí)第二種方法應(yīng)用的場景還是特別多的