TextViews Gravity不工作中心?

时间:2014-10-17 04:37:55

标签: android xml layout canvas draw

当我将TextView的绘图缓存绘制到Canvas时,TextView的Gravity在中心没有效果意味着没有在屏幕左侧设置的中心排列。

这里的类将TextViews画布绘制为自己的画布:

LinearLayout layout = new LinearLayout(
                            getApplicationContext());

                    TextView textView = new TextView(
                            getApplicationContext());
                    textView.setVisibility(View.VISIBLE);

                    textView.setText(str);
                    textView.setTextColor(myIntValue);
                    textView.setTypeface(tf);

                    textView.setTextSize(20);

                    // textView.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
                    textView.setGravity(Gravity.CENTER_HORIZONTAL);

                    layout.addView(textView);
                    layout.measure(c.getWidth(), c.getHeight());
                    layout.layout(0, 0, c.getWidth() / 2, c.getWidth() / 2);

                    c.translate(weight/2, Height / 2);

                    layout.draw(c);

2 个答案:

答案 0 :(得分:0)

尝试设置布局重力。

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
            LayoutParams. MATCH_PARENT, LayoutParams.WRAP_CONTENT);
params.gravity=Gravity.CENTER;
textView.setLayoutParams(params);

答案 1 :(得分:0)

而不是上面的代码使用此代码。它会很完美。

LinearLayout lLayout = new LinearLayout(this);
          lLayout.setOrientation(LinearLayout.VERTICAL); 
          LayoutParams lParams = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
          mTxtView = new TextView(this); mTxtView.setId(R.id.name);
          mTxtView.setTextSize(20); mTxtView.setGravity(Gravity.CENTER);
          mTxtView.setTextColor(Color.MAGENTA); mTxtView.setText("Country");
          lLayout.addView(mTxtView);
          setContentView(lLayout, lParams);