android - 如何以编程方式设置特定的宽度/高度以供查看?

标签 android android-layout

我在 xml 布局文件中有一个布局。
在运行时,我想创建 2 个 TextView 并将它们添加到布局中。
=> 我无法根据我的特定尺寸为 2 个 TextView 设置宽度/高度。
如果我设置 MATCH_PARENT,就可以了。
如果我按任何特定大小设置,它只是 WRAP_CONTENT

XML布局文件:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.androidsnipcode.MainActivity$PlaceholderFragment"
    android:orientation="vertical"
    android:id="@+id/mylayout">
</LinearLayout>


维度.xml:

<resources>
    <!-- Default screen margins, per the Android Design guidelines. -->
    <dimen name="activity_horizontal_margin">16dp</dimen>
    <dimen name="activity_vertical_margin">16dp</dimen>
    <dimen name="heigh">300dip</dimen>
    <dimen name="width">600dip</dimen>
</resources>

Activity.java 的onCreate():

LinearLayout layout = (LinearLayout) findViewById(R.id.mylayout);

        LinearLayout.LayoutParams layoutparams1 = new LinearLayout.LayoutParams(
                LayoutParams.MATCH_PARENT, R.dimen.heigh);
        TextView tv = new TextView(this);
        tv.setLayoutParams(layoutparams1);
        tv.setText("hello 1");
        tv.setBackgroundColor(Color.CYAN);
        layout.addView(tv);

        LinearLayout.LayoutParams layoutparams2 = new LinearLayout.LayoutParams(
                R.dimen.width, LayoutParams.MATCH_PARENT);
        TextView tv2 = new TextView(this);
        tv2.setLayoutParams(layoutparams2);
        tv2.setText("hello 2");
        tv2.setBackgroundColor(Color.MAGENTA);
        layout.addView(tv2);

屏幕截图:第一个 textview 的高度和第二个 textview 的宽度不符合我的预期(它是包装内容而不是我的特定尺寸)
height of first textview and width of second textview does not meet my expected

最佳答案

你可以这样做。宽度/高度应为像素值。

 ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(
  getResources().getDimensionPixelSize(R.dimen.width),100);

 textView.setLayoutParams(layoutParams);

您可以从维度资源读取或硬编码像素值。

关于android - 如何以编程方式设置特定的宽度/高度以供查看?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23113437/

相关文章:

Android - 当另一个线程完成某些操作时显示进度条

Android Room - 自动递增@database 版本号?

android - 在android中添加水印图片

android - 约束布局在底部有额外的空间

java - 在android中运行时更改项目单击上的GridView图像

android - Android 是否使用 minSdkVersion<24 对 Java 8 Iterable.forEach() 进行脱糖?

android - 在一个 Activity 和布局中使用几个ListView

java - fragment 中的 YouTubePlayerSupportFragment

android - 将 View 添加到现有 View 后面的相对布局会导致屏幕闪烁

android - 使用 screenSlider 和 Fragment 自动调整 TextView