自定義View之寬高的設置,全網最詳解

今天給大家帶來的是自定義View,然后如何設置他的寬高,經常用自定義view的程序猿肯定都知道我們在給自定義view設置wrap_content或者match_parent,view都會占滿全屏,就想如下

以下是方法,不提供自定義view的布局了,很簡單,就是繪一個藍色的圓

第一種方式(布局修改)

第一種方法也是最簡單的方法,我們直接給自定義view限制一個寬高

<?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>

效果如下

第二種方式(動態添加view修改寬高)

隨著我們的技術不斷提升,自定義view應用的場所也越來越多,如果我們動態的去添加自定義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
普通的動態添加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再添加一個寬高的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);
    }

效果

為什么和第一種有區別呢?原因很簡單,他們的單位不一樣,new RelativeLayout.LayoutParams(200,200);一個是像素單位,一個是dp單位
我們把這里的200全部改成400就和上面的一模一樣了

其實第二種方法應用的場景還是特別多的

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容