I'm trying to draw multiple custom views in a layout but only the first view I add it's drawn.
My custom view class is:
public ButtonView(Context context, int k) {
super(context);
this.setX(20+k*80);
init();
}
private void init(){
paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setColor(0x99ffffff);
}
@Override
protected void onDraw(Canvas cv){
cv.drawText(""+getX(), 0, 80, paint);
}
I'm displaying the text of the x coordinate in order to know which view is drawn.
This is the code of onCreate
of my main activity.
blay = (LinearLayout) this.findViewById(R.id.buttonslayout);
for(int k=0; k<10; k++){
ButtonView e = new ButtonView(this,k);
blay.addView(e);
}
When I run the application only the first view is drawn. I get a "20.0" displayed in white in the correct position, but the rest of the views are not showing. By debugging the app I realize that the instances of the views are created but for some reason they are not displayed. Also I tried to use invalidate
and override onMeasure
method but still not working.
I have modified your custom view please check if this is working.I guess the main problem with your code was that one view was occupying the whole screen. So I overridden onMeasure function
package com.example.stack2;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;
public class ButtonView extends View{
public ButtonView(Context context, int k) {
super(context);
//this.setX(20+k*80);
init();
}
public ButtonView(Context context, AttributeSet attrs, int defStyleAttr,
int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
// TODO Auto-generated constructor stub
}
public ButtonView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
// TODO Auto-generated constructor stub
}
public ButtonView(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}
public ButtonView(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
Paint paint;
private void init(){
paint = new Paint();
paint.setColor(Color.BLACK);
paint.setTextSize(20);
}
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// TODO Auto-generated method stub
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
//e.measure(0, 0);
getLayoutParams().width=100;
}
@Override
protected void onDraw(Canvas cv){
super.onDraw(cv);
cv.drawText(""+getX(), 0, cv.getHeight()/2, paint);
}
}
Also make sure the orientation of your linear layout is horizontal
Try to set some different color to each view..you will be able to see them.
Also set layout params to your custom views.