3

How can I centralise my text switcher? I've tried set gravity but it doesnt seem to work.

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;
    }
    });
beans
  • 1,765
  • 5
  • 25
  • 31
  • if you want to put your textview in center, then I think you used some parent layout and then apply android:layout_gravity="center". try this. Thanks. – user370305 Oct 05 '11 at 13:51
  • How can I add gravity to a linear layout programatically? Rather than xml. – beans Oct 05 '11 at 14:05

2 Answers2

2

If you are using match_parent or a fixed value for the TextSwitcher size, do the following. In the .xml:

<TextSwitcher
    android:id="@+id/switcher"
    android:layout_width="60dp"
    android:layout_height="60dp"/>   

In code:

    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;
        }
    });

It is quite important to set LayoutParams to MATCH_PARENT to get the TextSwitcher centered vertically.

Mario Velasco
  • 3,336
  • 3
  • 33
  • 50
2

That code is OK, you need to set the parent textSwitcher width to fill_parent

either in XML with

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

or in code

import android.widget.LinearLayout.LayoutParams;
//...
textSwitcher=...
textSwitcher.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
Daniel Fekete
  • 4,988
  • 3
  • 23
  • 23