美文网首页Android技术知识程序员Android开发
自定义View之宽高的设置,全网最详解

自定义View之宽高的设置,全网最详解

作者: 侯蛋蛋_ | 来源:发表于2017-09-27 10:31 被阅读0次

今天给大家带来的是自定义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就和上面的一模一样了

其实第二种方法应用的场景还是特别多的

相关文章

网友评论

    本文标题:自定义View之宽高的设置,全网最详解

    本文链接:https://www.haomeiwen.com/subject/ieuyextx.html