安卓开发设置视图的宽高

java yekong 395℃

视图宽度通过属性androidlayout_width表达,视图高度通过属性android:layout_heig
ht表达,宽高的取值主要有下列三种:
match_parent:表示与上级视图保持一致。
wrap_content:表示与内容自适应。
以dp为单位的具体尺寸。

xml设置宽高

<TextView
            android:id="@+id/tv_hello"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/name"
            android:textSize="30sp"
            android:textColor="#00ff00"
            android:background="@color/white"
            ></TextView>

java设置宽高

首先确保XML中的宽高属性值为wrap content,接着打开该页面对应的Java代码,依序
执行以下三个步骤:
调用控件对象的getLayoutParams方法,获取该控件的布局参数。
布局參数的width属性表示宽度,height属性表示高度,修改这两个属性值。
调用控件对象的setLayoutParams方法,填入修改后的布局参数使之生效。

package com.example.chapter03;

import android.graphics.Color;
import android.os.Bundle;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.example.chapter03.util.Utils;

public class TextViewActivity extends AppCompatActivity {
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_text_view);
        TextView tv_hello = findViewById(R.id.tv_hello);
        ViewGroup.LayoutParams params = tv_hello.getLayoutParams();
        params.width = Utils.dip2px(this, 300);
        tv_hello.setLayoutParams(params);
    }
}


分辨率转换

根据手机的分辨率从 dp 的单位 转成 px(像素)

package com.example.chapter03.util;

import android.content.Context;

//根据手机的分辨率从 dp 的单位 转成为 px(像素)
public class Utils {
    public static int dip2px(Context context, float dpValue) {
//        获取当前手机的像素密度(1个dp对应几px)
        float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }
}

喜欢 (0)