【问题标题】:Programmatically centering text in Android's Textview在 Android 的 Textview 中以编程方式居中文本
【发布时间】:2014-01-09 23:14:26
【问题描述】:

我创建了一个扩展 Android 文本视图的类。我正在尝试将文本水平和垂直居中。文本显示为水平居中,但不是垂直居中。

我都试过了:

setGravity(Gravity.CENTER);

setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);

我的课在下面:

public class NumberView extends TextView
{
  private Paint circlePaint;
  private int radius;

public NumberView(Context context)
{
    super(context);
    setText("0");
    circlePaint = new Paint();
    circlePaint.setColor(Color.BLUE);

//        setGravity(Gravity.CENTER);
    setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
    setBackgroundColor(Color.rgb(0xf1, 0xf1, 0xf1));

    setTypeface(null, Typeface.BOLD);
    setTextSize(TypedValue.COMPLEX_UNIT_SP, 15);

}

@Override
protected void onDraw(Canvas canvas) {
    // draw circle at center of canvas
    super.onDraw(canvas);
    int width = getWidth();
    int height = getHeight();
    radius = Math.min(width, height);
    radius /= 2;
    canvas.drawCircle(width/2, height/2, radius, circlePaint);

    //super.onDraw(canvas);
}

}

我将 NumberView 添加为 ExpandableList 视图的一部分。下面是我对布局的可扩展列表视图:

    listView = new ExpandableListView(this);
    listView.setAdapter(listAdapter);
    TextView emptyView = new TextView(this);

    listView.setEmptyView(emptyView);
    mainLayout.addView(listView,
            new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT , 2));

【问题讨论】:

  • 为什么不在 XML 布局文件中执行此操作?
  • 长话短说,我做不到。
  • 您将 NumberView textview 添加到布局的位置,请分享代码的相关部分
  • 您正在创建自定义文本视图,因此更改上面的代码 TextView emptyView = new TextView(this); to NumberView numberView=new NumberView(this);

标签: android user-interface textview center centering


【解决方案1】:
TextView emptyView = new TextView(this);

改成

NumberView numberView=new NumberView(this);

【讨论】:

    【解决方案2】:

    您必须使用您制作的 NumberView 类而不是 TextView 它会起作用,您也必须在 NumberView 上设置参数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-05
      • 2013-04-19
      • 1970-01-01
      相关资源
      最近更新 更多