如何在 LinearLayout 的任何 TextView 中使用属性 Gravity



你能解释一下为什么我的 TextView 不能在重力上工作吗?

在此处输入图像描述

答:线性布局 | 方向=水平 | 重力 A = 顶部或中心或底部。

B:线性布局 | 方向=垂直 | 重力 B = 左或中心或右。

C:文本视图

我我们:

A.set重力(gravity A(;

B.设置重力(重力B(;

结果重力:

  • 顶部 | 左 :不工作 (=顶部居中(

  • 居中 | 左 :不工作 (=居中(

  • 底部 | 左 :不工作 (=底部中心(

  • 首页 | 中心 :工作中心

  • 中心
  • | 中心 :工作中心

  • 底部 | 中心:工作

  • 上 | 右 :工作

  • 居中 | 右:工作

  • 底部 | 右 :工作

    LinearLayout parent = new LinearLayout(mContext);
    LinearLayout framelayoutTitle = new LinearLayout(mContext);
    framelayoutTitle.setOrientation(LinearLayout.HORIZONTAL);
    framelayoutTitle.setGravity(vGravityTitle);
    LinearLayout layoutTitle = new LinearLayout(mContext);
    layoutTitle.setOrientation(LinearLayout.VERTICAL);
    layoutTitle.setGravity(hGravityTitle);
    holder.textTitle = new TextView(mContext);
    layoutTitle.setLayoutParams( new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
    
    framelayoutTitle.setLayoutParams(new LinearLayout.LayoutParams((widthTitle * (width - dp2px(widthImageLV))) / 100, dp2px(heightTitle)));    
    
    holder.textTitle.setText(titleList.get(position));
    holder.textTitle.setGravity(alignmentTextTitle);
    holder.textTitle.setLayoutParams( new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
    holder.textTitle.setTextSize(sizeTitle);
    holder.textTitle.setBackgroundColor(Color.WHITE);
    layoutTitle.addView(holder.textTitle);
    framelayoutTitle.addView(layoutTitle);
    parent.setOrientation(LinearLayout.HORIZONTAL);
    parent.setGravity(Gravity.TOP);
    parent.addView(framelayoutTitle);
    

试试这个,并根据您的需要提供填充和边距。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textView"
android:text="A"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textView2"
android:text="b"
android:layout_below="@+id/textView"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textView3"
android:text="b"
android:layout_below="@+id/textView2"
android:layout_centerHorizontal="true"
/>
</RelativeLayout>

最新更新