XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="视图宽高采用wrap_content定义"
android:textColor="#000000"
android:background="#00ff00"
android:layout_marginTop="5dp"
android:textSize="17sp"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="视图宽高采用match_parent定义"
android:textColor="#000000"
android:background="#00ff00"
android:layout_marginTop="5dp"
android:textSize="17sp"/>
<TextView
android:layout_width="300dp"
android:layout_height="wrap_content"
android:text="视图宽高采用固定大小"
android:textColor="#000000"
android:background="#00ff00"
android:layout_marginTop="5dp"
android:textSize="17sp"/>
<TextView
android:id="@+id/tv_code"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="通过代码指定视图宽度"
android:textColor="#000000"
android:background="#00ff00"
android:layout_marginTop="5dp"
android:textSize="17sp"/>
</LinearLayout>Java
package com.example.chapter003;
import android.os.Bundle;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import com.example.chapter003.Utils.Utils;
public class ViewBorderActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_border);
TextView tv_code = findViewById(R.id.tv_code);
ViewGroup.LayoutParams Params = tv_code.getLayoutParams();
Params.width = Utils.dip2px(this, 300);
tv_code.setLayoutParams(Params);
}
}Java
package com.example.chapter003.Utils;
import android.content.Context;
public class Utils {
public static int dip2px(Context context,float dpValue){
float scale = context.getResources().getDisplayMetrics().density;
return (int)(dpValue * scale + 0.5f);
}
}以上代码展示的是设置视图的宽和高,由于Activity仅支持设置像素,所以定义了Utils.dip2px来根据设备实际情况将dp转化为px。