Android,如何将文本切换器置于中央?

3
如何将文本切换器居中显示?我尝试了设置重力,但似乎没有起作用。
ts.setFactory(new ViewFactory() {
        public View makeView() {
        TextView t = new TextView(this);
        t.setTypeface(tf);
        t.setTextSize(20);
        t.setTextColor(Color.WHITE);
        t.setText("my text switcher");
        t.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
        return t;
    }
    });

如果您想将TextView置于中心位置,我认为您需要使用一些父布局,然后应用android:layout_gravity="center"。请尝试这样做。谢谢。 - user370305
我该如何在程序中为线性布局添加重力效果?而不是使用XML。 - beans
2个回答

2

那段代码没问题,你需要将父级textSwitcher的宽度设置为fill_parent

可以在XML中使用以下方式:

<TextSwitcher android:layout_width="fill_parent" ...

或者在代码中。
import android.widget.LinearLayout.LayoutParams;
//...
textSwitcher=...
textSwitcher.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));

在运行时获取TextSwitcher的文本是否可行? - Karthi

2
如果您正在使用match_parent或固定值来设置TextSwitcher的大小,请按照以下步骤进行操作。在.xml文件中:
<TextSwitcher
    android:id="@+id/switcher"
    android:layout_width="60dp"
    android:layout_height="60dp"/>   

在代码中:
    import android.widget.FrameLayout.LayoutParams;

    TextSwitcher mSwitcher = (TextSwitcher) findViewById(R.id.switcher);
    mSwitcher.setFactory(new ViewFactory() {
        @Override
        public View makeView() {
            TextView t = new TextView(MainActivity.this);
            t.setGravity(Gravity.CENTER);
            t.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
            return t;
        }
    });

将LayoutParams设置为MATCH_PARENT非常重要,以便使TextSwitcher在垂直方向上居中。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接