【发布时间】:2014-07-19 03:13:09
【问题描述】:
我有一个问题。我正在尝试创建具有规格尺寸的 TextView,并且我在 onMeasure 方法中执行此操作。我的问题是我想更改 textalignment,所以我调用 setGravity(Gravity.RIGHT) 方法但它不是工作,文本仍在左侧。
以下是我的代码,希望有人能帮助我:(
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout layout = new LinearLayout(this);
MyLabel label = new MyLabel(this);
label.setText("Hello");
label.setBackgroundColor(Color.RED);
label.setGravity(Gravity.RIGHT);
layout.addView(label);
setContentView(layout);
}
public class MyLabel extends TextView {
public MyLabel(Context context) {
super(context);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
// Desire Size : Mac dinh la Wrap Content
float desireWidth = getMeasuredWidth();
float desireHeight = getMeasuredHeight();
int maxWidth = 0;
int maxHeight = 0;
float width = 0.7f;
float height = 0.3f;
if (maxWidth == 0) {
maxWidth = MeasureSpec.getSize(widthMeasureSpec);
}
if (maxHeight == 0) {
maxHeight = MeasureSpec.getSize(heightMeasureSpec);
}
// Neu abstract model co thong tin ve kich thuoc :
if (width > 0) {
int parentWidth = 0;
if (true) {
parentWidth = maxWidth;
} else {
parentWidth = 480;
}
if (width <= 1) {
// Gia tri duoc tinh toan theo % cua parent
desireWidth = width * parentWidth;
} else {
desireWidth = width < parentWidth ? width : parentWidth;
}
}
// Kich thuoc chieu cao cung tuong tu nhu vay
if (height > 0) {
int parentHeight = 0;
if (true) {
parentHeight = maxHeight;
} else {
parentHeight = 800;
}
if (height <= 1) {
// Gia tri duoc tinh toan theo % cua parent
desireHeight = height * parentHeight;
} else {
desireHeight = height < parentHeight ? height
: parentHeight;
}
}
// Cuoi cung, ta set kich thuoc cho view
this.setMeasuredDimension((int) desireWidth, (int) desireHeight);
}
};
【问题讨论】:
-
不是重复的,该问题涉及静态 xml 布局而不是动态代码生成的布局。
-
我认为你的重力没有问题。只需为你的布局设置一个大小,比如 match_parent.den 看看你的文本 z 是否在右边。
标签: android