我遇到了自定义textview的问题。 我创建了自定义视图,它很好,但现在我试图将它集中在父级中:
android:layout_centerHorizontal = true
但它不以父级为中心,即使我设置了
,它也不会占用所有可用空间android:layout_width="fill_parent"
这是我自定义文本视图的代码:
public class GlowTextView extends TextView{
private Context context;
private AttributeSet attr;
private static final String COLOR = "#9bdb9d";
private static final String SHADOW_COLOR = "#26db2b";
public String ora = "00:00"; //il testo che verra' disegnato
/*handler per il ritardo dell' orologio*/
Handler handler = new Handler();
/*Calendar per il recupero dell' ora*/
private Calendar calendar;
private Paint paint = new Paint();
public GlowTextView(Context context) {
super(context);
this.context = context;
handler.post(sendData); //faccio partire il timer per l' ora
}
public GlowTextView(Context context, AttributeSet attrs) {
super(context, attrs);
this.context = context;
this.attr = attrs;
handler.post(sendData);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
setText(ora);
//setTextSize(size); //grandezza del testo
setTextColor(Color.parseColor(COLOR));
setShadowLayer(15, 0, 0, Color.parseColor(SHADOW_COLOR));
setTypeface(Typeface.createFromAsset(context.getAssets(), "fonts/Neon.ttf")); //font per l' ora
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int reqWidth;
int reqHeight;
reqWidth = (int)(ora.length() * this.getTextSize());
reqHeight = (int) this.getTextSize();
// set the calculated width and height of your drawing area
setMeasuredDimension(reqWidth, reqHeight);
}
private void setClockText(String text) {
setText(text);
invalidate();
}
/*
* delay per l' aggiornamento dell' orologio
*/
private final Runnable sendData = new Runnable(){
public void run(){
try {
/*Recuper l' ora*/
calendar = Calendar.getInstance();
String minute = Integer.toString(calendar.get(Calendar.MINUTE));
if(minute.length() == 1) minute = '0' + minute;
String hour = Integer.toString(calendar.get(Calendar.HOUR_OF_DAY));
if(hour.length() == 1) hour = '0' + hour;
ora = hour + ":" + minute;
/*Passo l' ora alla textview
*/
setClockText(ora);
Log.d("Delay", "Refresh clock!");
handler.postDelayed(this, 15000);
}
catch (Exception e) {
e.printStackTrace();
}
}
};
}
答案 0 :(得分:0)
尝试调整布局的重力
如果你的TextView有layout_width =“match_parent”:
<package.name.customTextView
android:id="@+id/myCustomTextView"
android:gravity="center_horizontal"
...
如果你的textView有layout_width =“wrap_content”
<package.name.customTextView
android:id="@+id/myCustomTextView"
android:layout_gravity="center_horizontal"
...
希望这有帮助,快乐编码!