以编程方式居中 TextView 文本 [英] Programmatically center TextView text

查看:22
本文介绍了以编程方式居中 TextView 文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在此请求一些宽大处理,我只是从 Android SDK 教程开始,我正在尝试一些不在本教程中的兴趣,但我希望会很容易.

I beg some leniency here, I'm just starting with the Android SDK tutorials and I'm attempting something out of interest that's not in the tutorial itself, but I would hope would be easy.

我正在尝试通过代码水平和垂直居中 TextView 项目(我可以在 XML 中很好地做到这一点).当父对象是表格或其他对象时,我已经看到了几个如何执行此操作的示例,但我希望这对我来说更容易掌握.(附注:请随时更正我的术语).

I am trying to center a TextView item via code horizontally and vertically (I can do it in XML just fine). I've seen several examples of how to do this when the parent is a table or some other object, but I hope this would be easier for me to grasp. (p.s. Feel free to correct my terminology).

这是教程/我的工作模型中的示例代码:

Here is the example code from the tutorial / my working model:

package com.example.myfirstapp;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.ViewGroup.LayoutParams;
import android.widget.TextView;


public class DisplayMessageActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Intent intent = getIntent();
        String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);

        TextView textView = new TextView(this);
        textView.setTextSize(40);
        textView.setText(message);
        textView.setGravity(View.TEXT_ALIGNMENT_GRAVITY);

        setContentView(textView);
    }
}

我已设法找到 setGravity 方法,并尝试涉足 setLayoutParams 方法,但我不确定范围是什么因为我找不到我应该导入什么来获得 WRAP_CONTENT 常量来解析.据我了解,居中和 content_wrapping+gravity 是两个不同的东西.我想要一个在这种情况下如何做的例子,也许我会如何/在哪里找到 API 文档中的答案?

I've managed to locate the setGravity method, and I've tried to dabble in the setLayoutParams for it, but I'm not sure what the scope is for it as I can't locate what I should be importing to get the WRAP_CONTENT constant to resolve. From what I understood, centering and content_wrapping+gravity are two separate things. I'd like an example of how to do both in this case and maybe how/where I would have found the answer in the API documentation?

推荐答案

yourTextView.setGravity(Gravity.CENTER);

这篇关于以编程方式居中 TextView 文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆