Question about android.view.Gravity

I’m trying to center some text at the top of the screen using android.view.Gravity, but it looks like it’s just getting ignored. I’m not getting any error message, either at compile time or run time, but the text is still left-justified, not centered.

Here’s my procedure to add some text:

void textView(int x, int y, int w, color txtColor, float txtSize, String text) {

  TextView textView = new TextView(ctx);
  textView.setLayoutParams (new RelativeLayout.LayoutParams(
    RelativeLayout.LayoutParams.WRAP_CONTENT, 
    RelativeLayout.LayoutParams.WRAP_CONTENT));
  textView.setX(x);
  textView.setY(y);
  textView.setWidth(w);
  textView.setTextColor(txtColor);
  textView.setTextSize(txtSize);
  textView.setGravity(CENTER);    // center text
  textView.setText(text);
  FrameLayout flayout = (FrameLayout)activity.findViewById(R.id.content);
  flayout.addView(textView);
}

I’m calling it with this statement:

textView(0, 60, width, BLACK, textSize*2, "Korg NTS-1 Control Panel");

What am I doing wrong? Or doesn’t this work in Android mode?

Thanks.

Never mind, I found the problem. Something else was masking the value for ‘CENTER’. I had to change the line to:

textView.setGravity(Gravity.CENTER);

I’ll leave this here, though, in case someone else has the same problem.

1 Like