【问题标题】:center text in TextView programmatically以编程方式在 TextView 中居中文本
【发布时间】:2013-01-30 22:39:23
【问题描述】:

我以编程方式创建了一个带有文本和背景可绘制对象的 TextView。我想将 TextView 中的文本居中,但文本居中在顶部。

这是我在 TextView 中居中文本的代码:

protected class TileView extends TextView{
    private int tileType;
    private int col;
    private int row;

protected TileView(Context context, int row, int col, int tileType) {

    super(context);
    this.col = col;
    this.row = row;
    this.tileType = tileType;

    String result = Integer.toString(RandomNumber(1,9));            
    Drawable image = getResources().getDrawable(tile_id[tileType]);
    setBackgroundDrawable(image);
    setClickable(true);
    setText(result);        
    setTextAppearance(context, R.style.boldText);           
    setOnClickListener(GameView.this);
}
}

这是我在 onLayout() 中的代码

int left = oneFifth * tileView.getCol();
int top = oneFifth * tileView.getRow();
int right = oneFifth * tileView.getCol() + oneFifth;
int bottom = oneFifth * tileView.getRow() + oneFifth;
tileView.layout(left, top, right, bottom);
tileView.setGravity(Gravity.CENTER);

如何让 TextView 中的文本居中?

【问题讨论】:

    标签: android android-layout textview


    【解决方案1】:

    试试这个希望对你有帮助

    textView.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);   
    
     yourTextView.setGravity(Gravity.CENTER);
    

    检查这个Link

    【讨论】:

    • 我已经将它包含在 onLayout 函数中,但它不起作用。
    • textView.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);添加这个
    • 将 setGravity(Gravity.CENTER) 更改为那个,但它也不起作用。
    • @Mirage01 创建相对布局添加试试上面添加的链接
    • 我的布局是线性布局。你的意思是我要把它改成RelativeLayout?
    【解决方案2】:

    你可以这样做:

    textView.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
    

    【讨论】:

      【解决方案3】:

      我使用android:gravity="center_vertical|center_horizontal"将我的文本放在.XML 中

      【讨论】:

      • TextView 是以编程方式创建的,而不是在 XML 中。
      • ah.. sry.. 然后和 AlexGo 一样说
      【解决方案4】:

      您必须将其添加到 layoutparams 中,例如:

      LayoutParams params = new LayoutParams(
                      LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT);
                  params.weight = 1.0f;
                  params.gravity=17;
      

      17 是 docs 中的 CENTER 常量。

      【讨论】:

      • params 没有重量和重力的属性
      • 尝试导入 LinearLayout.LayoutParams ,在docs
      猜你喜欢
      • 1970-01-01
      • 2014-01-09
      • 2019-03-05
      • 2013-04-19
      • 2016-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-12
      相关资源
      最近更新 更多