I have a problem.I'm trying to create TextView with specification dimensions, and i do it in onMeasure method.My progblem is i want to change the textalignment, so i call setGravity(Gravity.RIGHT) method but it's not working, the text is still in left side.
Below is my code, i hope someone'll help me :(
@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);
}
};