有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java TextView在运行时扩展

我在这个文本视图的右边有一个文本框和一个图像视图。如果图像URL不可用,我会使此图像视图的可见性消失。现在我想将TextView宽度扩展为MatchParent。但它不起作用。有点不对劲,我想不出来。我需要帮助。代码如下所示

我尝试了StackOverflow中的所有解决方案,但有些确实不起作用

请帮忙

                if (ImageURL.equals(null)){
            holder.Image.setVisibility(View.GONE);
//            RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams)
//            holder.question.setLayoutParams();
//            layoutParams.width = RelativeLayout.LayoutParams.MATCH_PARENT;
            holder.question.setLayoutParams(new ViewGroup.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
//            holder.question.setLayoutParams(layoutParams);
        }

共 (2) 个答案

  1. # 1 楼答案

    试试这段代码,不需要设置布局参数

        <TextView
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="10"
            android:text="sadasdasdasdasdasdasdasdasdsadasdasd" />
    
        <ImageView
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="3"
            android:src="@mipmap/ic_launcher"
            android:visibility="visible" />
    </LinearLayout>
    
  2. # 2 楼答案

    在这种情况下,约束布局更灵活。不再鼓励使用RelativeLayout

    <androidx.constraintlayout.widget.ConstraintLayout
            xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:tools="http://schemas.android.com/tools"
            xmlns:app="http://schemas.android.com/apk/res-auto"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            tools:context=".MainActivity">
    
        <TextView
                android:id="@+id/textView"
                app:layout_constraintTop_toTopOf="parent"
                app:layout_constraintEnd_toStartOf="@+id/imageView"
                app:layout_constraintStart_toStartOf="parent"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:text="Hello World!"/>
    
        <ImageView
                app:layout_constraintStart_toEndOf="@+id/textView"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintTop_toTopOf="parent"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                tools:srcCompat="@tools:sample/avatars"
                android:id="@+id/imageView"
                android:layout_alignParentEnd="true"/>
    
    </androidx.constraintlayout.widget.ConstraintLayout>
    

    要使TextView占据整个宽度,只需将ImageViewvisibility更改为GONE

    imageView.visibility = GONE