编程中心的TextView文本 [英] Programmatically center TextView text

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

问题描述

我在这里乞求一些宽大处理,我刚开始使用Android SDK教程,我尝试出来的东西感兴趣,这不是在本教程本身,而是我希望会是容易的。

我想水平居中通过code一个TextView项目和垂直(我可以在XML就好做)。我已经看到了如何做到这一点的时候父母是表或其他对象的几个例子,但我希望这将是我更容易把握。 (附注:随时纠正我的术语)。

下面是本教程中/我的工作模型的例子code:

 包com.example.myfirstapp;

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


公共类DisplayMessageActivity延伸活动{
    @覆盖
    公共无效的onCreate(包savedInstanceState){
        super.onCreate(savedInstanceState);
        意向意图= getIntent();
        字符串消息= intent.getStringExtra(MainActivity.EXTRA_MESSAGE);

        TextView中的TextView =新的TextView(本);
        textView.setTextSize(40);
        textView.setText(消息);
        textView.setGravity(1);

        的setContentView(TextView的);
    }
}
 

我已经成功地找到setGravity方法,我已经试过了setLayoutParams为它涉足,但我不知道的范围是什么,因为我无法找到我应该导入到获得WRAP_CONTENT不断解决。从我的理解,居中和content_wrapping +重力是两回事。我想如何在这种情况下,两者都做一​​个例子,也许如何/在哪里我会找到API文档中的答案吗?

解决方案

  yourTextView.setGravity(Gravity.CENTER);
 

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.

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(1);

        setContentView(textView);
    }
}

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天全站免登陆