【问题标题】:How to set specific width/height for view programmatically?如何以编程方式为视图设置特定的宽度/高度?
【发布时间】:2014-04-16 15:12:09
【问题描述】:

我在 xml 布局文件中有一个布局。
在运行时,我想创建 2 个文本视图并将它们添加到布局中。
=> 我无法按我的特定尺寸设置 2 个文本视图的宽度/高度。
如果我设置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>


Dimens.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 的宽度不符合我的预期(它的包装内容不是我的特定大小)

【问题讨论】:

    标签: android android-layout


    【解决方案1】:

    你可以这样做。宽度/高度应该是一个像素值。

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

    您可以从尺寸资源中读取或硬编码像素值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-23
      • 2011-06-29
      • 1970-01-01
      • 2016-10-27
      • 2011-03-09
      • 1970-01-01
      • 1970-01-01
      • 2019-02-03
      相关资源
      最近更新 更多