Can we create a canvas programmatically from a view in Android - android

I am trying to create a dummy view from already existing View.
Original Image:
Need to create dummy view like this.
I tried with paint and canvas.
public class MyView extends View {
Paint paint;
Path path;
public MyView(Context context) {
super(context);
init();
}
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public MyView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init(){
paint = new Paint();
paint.setColor(Color.BLUE);
paint.setStrokeWidth(10);
paint.setStyle(Paint.Style.STROKE);
}
#Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
canvas.drawRect(30, 50, 200, 350, paint);
// canvas.drawRect(100, 100, 300, 400, paint);
//drawRect(left, top, right, bottom, paint)
}
}
But I cannot draw like this. Because some time image will be circle or Ovel or any shape. So, I need to deduct the existing view and draw new view as same. Can anyone help me to create a dummy view from existing view?
I am trying to do this for shimmer animation only. For facebook shimmer I need to give the view inside the shimmerFramelayout. But My view will be dynamic. So, I need to create a dummy view programmatically for every time. For facebook Shimmer:
<com.facebook.shimmer.ShimmerFrameLayout
android:id="#+id/shimmerLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:ignore="MissingConstraints">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<!--add several shimmer placeholder layout -->
<include layout="#layout/shimmer_placeholder_layout"></include>
<include layout="#layout/shimmer_placeholder_layout"></include>
<include layout="#layout/shimmer_placeholder_layout"></include>
</LinearLayout>
</com.facebook.shimmer.ShimmerFrameLayout>
Here shimmer_placeholder_layout is static view. I need to create dynamic view.

Finally got the solution.
Here I attached the solution for someone will get benefit on this.
MyView class:
public class MyView extends View {
Paint paint;
ViewGroup viewGroup;
Context context;
List<Rect> rectList = new ArrayList<>();
public MyView(Context context, ViewGroup viewGroup) {
super(context);
this.viewGroup = viewGroup;
this.context = context;
init();
}
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public MyView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init() {
paint = new Paint();
paint.setColor(context.getResources().getColor(R.color.gray));
paint.setStrokeWidth(10);
paint.setStyle(Paint.Style.FILL);
for (int i = 0; i < viewGroup.getChildCount(); ++i) {
View child = viewGroup.getChildAt(i);
Rect rect = new Rect();
int x = (int) child.getX() - dpToPx(20);
int y = (int) child.getY() - dpToPx(20);
rect.left = x;
rect.top = y;
rect.right = x + child.getWidth();
rect.bottom = y + child.getHeight();
rectList.add(rect);
}
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
for (Rect rect : rectList) {
canvas.drawRect(rect, paint);
}
}
public static int dpToPx(int dp) {
return (int) (dp * Resources.getSystem().getDisplayMetrics().density);
}
}
My MainActivity:
ConstraintLayout constraintLayout;
ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
constraintLayout = findViewById(R.id.parent_view);
imageView = findViewById(R.id.item_profile_img);
constraintLayout.post(() -> {
ShimmerFrameLayout shimmerFrameLayout = new ShimmerFrameLayout(MainActivity.this);
Shimmer shimmer = new Shimmer.ColorHighlightBuilder()
.setDuration(2000)
.setBaseAlpha(0.9f)
.setHighlightAlpha(0.93f)
.setWidthRatio(1.5f)
.setDirection(Shimmer.Direction.RIGHT_TO_LEFT)
.setAutoStart(true)
.setBaseColor(getColor(android.R.color.darker_gray))
.setBaseColor(getColor(android.R.color.darker_gray))
.setHighlightColor(getColor(android.R.color.white))
.build();
shimmerFrameLayout.setShimmer(shimmer);
shimmerFrameLayout.addView(new MyView(MainActivity.this,constraintLayout));
constraintLayout.addView(shimmerFrameLayout);
shimmerFrameLayout.startShimmer();
});
}
My activity_main.xml:
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:ignore="HardcodedText,MissingConstraints"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<androidx.constraintlayout.widget.ConstraintLayout
tools:ignore="HardcodedText,MissingConstraints"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="20dp"
android:id="#+id/parent_view">
<ImageView
android:id="#+id/item_profile_img"
android:layout_width="100dp"
android:layout_height="100dp"
android:src="#drawable/ic_launcher_background"
app:layout_constraintTop_toTopOf="parent"
tools:ignore="ContentDescription,MissingConstraints" />
<TextView
android:id="#+id/item_student_name_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="15dp"
android:text="Student name"
android:textStyle="bold"
app:layout_constraintStart_toEndOf="#+id/item_profile_img" />
<TextView
android:id="#+id/item_student_college"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="15dp"
android:layout_marginTop="8dp"
android:text="Student college"
app:layout_constraintStart_toEndOf="#+id/item_profile_img"
app:layout_constraintTop_toBottomOf="#+id/item_student_name_title" />
<TextView
android:id="#+id/item_student_specialization"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="15dp"
android:layout_marginTop="8dp"
android:text="Student specialization"
app:layout_constraintStart_toEndOf="#+id/item_profile_img"
app:layout_constraintTop_toBottomOf="#+id/item_student_college" />
<TextView
android:id="#+id/item_student_description"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="15dp"
android:layout_marginTop="8dp"
android:text="Student description"
app:layout_constraintTop_toBottomOf="#+id/item_profile_img"
tools:ignore="MissingConstraints" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.constraintlayout.widget.ConstraintLayout>

Related

How to draw a Line between two ImageViews by getting the positions of the ImageViews?

This is MainActivity.java code which gets the positions of the imagViews and tries to generate a lineView between the ImageViews by getting the coordinates of the ImageViews.
I'm getting the coordinates of the ImageViews but it's not showing the line between them.
public class MainActivity extends AppCompatActivity {
private ImageView one,two;
private LineView lineView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lineView=findViewById(R.id.lineView);
one=findViewById(R.id.one);
two=findViewById(R.id.two);
Random random = new Random();
int x=random.nextInt(500);
int y=random.nextInt(500);
one.setX(x);
one.setY(y);
int c=x;
int d=y;
PointF pointA=new PointF(c,d);
x=random.nextInt(500);
y=random.nextInt(500);
two.setX(x);
two.setY(y);
c=x;
d=y;
PointF pointB=new PointF(c,d);
lineView.setPointA(pointA);
lineView.setPointB(pointB);
lineView.draw();
}
}
This is activity_main.xml that contains the ImageViews and LineView.
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
<xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
>
<ImageView
android:id="#+id/one"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="116dp"
android:layout_marginTop="197dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/one" />
<ImageView
android:id="#+id/two"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="133dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/two" />
<com.example.testing.LineView
android:id="#+id/lineView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</android.support.constraint.ConstraintLayout>
This is the Lineview.java code that generates the line view widget and its operations .
public class LineView extends View {
PointF pointA,pointB;
private Paint paint =new Paint();
public LineView(Context context) {
super(context);
}
public LineView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public LineView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
paint.setColor(Color.RED);
paint.setStrokeWidth(20);
canvas.drawLine(pointA.x,pointA.y,pointB.x,pointB.y,paint);
}
public void setPointA(PointF point)
{
pointA=point;
}
public void setPointB(PointF point)
{
pointB=point;
}
public void draw()
{
invalidate();
requestLayout();
}
}
You can do it in your view - put this View between your images:
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#android:color/black" />
The horizontal line between two image views in android
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#FF0000FF"/>
The vertical line between two image views in android
<View
android:layout_width="1dp"
android:layout_height="match_parent"
android:background="#FF0000FF"/>

Single custom view multiple shape animation

If a custom view has several shapes, Is it possible to animate only one of them?
For eg: for one of my application, 2 circles, one inner and another outer are drawn on a custom view. While I tried to animate using scale animation, I see that both the circles gets animated where as I need only one of them to.
One of the solution that occurred to me is to have multiple custom views.
But not sure if it is the right way to do it.
Are there alternate better solution to it?
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<com.test.customanimation.CustomView
android:id="#+id/circular_progress"
android:layout_width="400dp"
android:layout_height="400dp"
android:layout_gravity="center"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
<Button
android:id="#+id/scale_up"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Scale Up"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
/>
<Button
android:id="#+id/scale_down"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:text="Scale Down"/>
</android.support.constraint.ConstraintLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity {
private CustomView mCustomView;
private Button mScaleUpBtn;
private Button mScaleDownBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mCustomView = findViewById(R.id.circular_progress);
mScaleUpBtn = findViewById(R.id.scale_up);
mScaleUpBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mCustomView.scaleUpAnimation(5000);
}
});
mScaleDownBtn = findViewById(R.id.scale_down);
mScaleDownBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mCustomView.scaleDownAnimation(5000);
}
});
}
}
CustomView.java
public class CustomView extends View {
private Paint OuterCirclePaint,InnerCirclePaint;
float mCircleX,mCircleY,mInnerCircleRadius,mOuterCircleRadius;
public CustomView(Context context) {
super(context);
init();
}
public CustomView(Context context, #Nullable AttributeSet attrs) {
super(context, attrs);
init();
}
public CustomView(Context context, #Nullable AttributeSet attrs, int
defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
public CustomView(Context context, #Nullable AttributeSet attrs, int
defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init();
}
private void init(){
OuterCirclePaint = new Paint();
OuterCirclePaint.setColor(Color.GREEN);
OuterCirclePaint.setStrokeWidth(20);
OuterCirclePaint.setStyle(Paint.Style.STROKE);
InnerCirclePaint = new Paint();
InnerCirclePaint.setColor(Color.BLACK);
InnerCirclePaint.setStyle(Paint.Style.FILL_AND_STROKE);
}
#Override
protected void onDraw(Canvas canvas) {
mCircleX = getWidth()/2;
mCircleY = getHeight()/2;
if(mCircleX < mCircleY) {
mInnerCircleRadius = (getWidth() / 2) - 100;
mOuterCircleRadius = (getWidth() / 2) - 40;
}
else {
mInnerCircleRadius = (getHeight() / 2) - 100;
mOuterCircleRadius= (getHeight() / 2) - 40;
}
canvas.drawCircle(mCircleX,mCircleY,mOuterCircleRadius,OuterCirclePaint);
canvas.drawCircle(mCircleX,mCircleY,mInnerCircleRadius,InnerCirclePaint);
}
public void scaleDownAnimation(int duration){
ScaleAnimation fade_in = new ScaleAnimation(1.0f,0.5f,1.0f,0.5f,
Animation.RELATIVE_TO_SELF,0.5f,Animation.RELATIVE_TO_SELF,0.5f);
fade_in.setDuration(duration);
fade_in.setFillAfter(true);
this.startAnimation(fade_in);
}
public void scaleUpAnimation(int duration){
ScaleAnimation fade_out = new ScaleAnimation(0.5f,1.0f,0.5f,1.0f,
Animation.RELATIVE_TO_SELF,0.5f,Animation.RELATIVE_TO_SELF,0.5f);
fade_out.setDuration(duration);
fade_out.setFillAfter(true);
this.startAnimation(fade_out);
}
}
You are already overriding onDraw() and providing your own methods to handle the animations. IMO this approach is best for performance, so I'd keep it that way and only switch over to another animation framework, namely Property Animations
In order to redraw only the inner circle during an animation, I'd suggest using ValueAnimator and ValueAnimator.AnimatorUpdateListener for the animations.
Let's introduce some new fields for CustomView
private float scaleFactor = 1f;
private ValueAnimator scaleUpAnimator;
private ValueAnimator scaleDownAnimator;
private ValueAnimator.AnimatorUpdateListener updateListener;
Initialize them as follows
private void initAnimations() {
scaleUpAnimator = ValueAnimator.ofFloat(0.5f, 1.0f);
scaleDownAnimator = ValueAnimator.ofFloat(1.0f, 0.5f);
updateListener = new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator animation) {
scaleFactor = (float)animation.getAnimatedValue();
CustomView.this.invalidate();
}
};
scaleUpAnimator.addUpdateListener(updateListener);
scaleDownAnimator.addUpdateListener(updateListener);
}
Change the line for the inner circle in onDraw()
canvas.drawCircle(mCircleX, mCircleY, mInnerCircleRadius * scaleFactor, innerCirclePaint);
... and start the animations like this
public void scaleDownAnimation(int duration){
scaleDownAnimator.setDuration(duration);
scaleDownAnimator.start();
}
public void scaleUpAnimation(int duration){
scaleUpAnimator.setDuration(duration);
scaleUpAnimator.start();
}

custom view placing horizontally central on RelativeLayout

I am trying to place my custom view horizontally centered on a Relative Layout.
However it does not appear centered, instead it is close to the left of the screen.
Below is my xml file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="5sp"
tools:context=".FinalActivity" >
<ImageView
android:contentDescription="#string/none"
android:id="#+id/imageView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:layout_marginLeft="0px"
android:layout_marginTop="0px"
android:scaleType="fitXY"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:src="#drawable/oven_alt" />
<com.test.game.myviewx
android:id="#+id/xview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
/>
<ImageView
android:contentDescription="#string/none"
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:layout_marginLeft="0px"
android:layout_marginTop="0px"
android:scaleType="fitXY"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:src="#drawable/oven_ust" />
</RelativeLayout>
and here is the custom view class:
public class myviewx extends View
{
Context cntx;
public myviewx(Context context) {
super(context);
cntx = context;
// TODO Auto-generated constructor stub
}
public myviewx(Context context, #Nullable AttributeSet attrs) {
super(context, attrs);
cntx = context;
// TODO Auto-generated constructor stub
}
public myviewx(Context context, #Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
cntx = context;
}
#Override
protected void onDraw(Canvas canvas)
{
super.onDraw(canvas);
final String MY_PREFS_NAME = "MyPrefsFile";
SharedPreferences sharedPreferences = cntx.getSharedPreferences(MY_PREFS_NAME, Context.MODE_PRIVATE);
Integer pb = sharedPreferences.getInt("pb", 0);
Bitmap bitmap;
Resources res = getResources();
if (pb==1) {
bitmap = BitmapFactory.decodeResource(res, R.drawable.p1);
}
else {
bitmap = BitmapFactory.decodeResource(res, R.drawable.p2);
}
//int x=500;
//int y=500;
//int radius=250;
Paint paint=new Paint();
// Use Color.parseColor to define HTML colors
//paint.setColor(Color.parseColor("#CD5C5C"));
//canvas.drawRect (250,250, 750, 750, paint);
//paint.setColor(Color.parseColor("#CD000C"));
//canvas.drawCircle(x,x, radius, paint);
canvas.drawBitmap(bitmap, 0, 0, paint);
}
}
using parameter "android:layout_centerHorizontal="true"" , imageviews are centered but "com.test.game.myviewx" custom view is not centered.
what am I missing ?
I had the same problem and could not find a solution.
Ended up drawing the content of the view centered.
You can use "this.getWidth()" and then draw everything accordingly.

Linking XML with Component View

I'm currently struggling with what I believe should be pretty simple.
I have created a LinearLayout in an XML file that i want to link to a CustomComponent that extends LinearLayout, meaning i started backwards.
Normally i create a CustomComponent first and this creates an XML-file linked by a tag, <my.package.CustomComponent> (If I'm not mistaken this is the only way they are linked(?)) and i do stuff in the onDraw(). But in this project i do the layout throughthe XML and not the onDraw().
Linking XML with activity is done by setContentView(R.layout.customView) but I can't really do this in a CustomComponent as i don't have an onCreate() method inherited.
sidenote: In the XML all my imagebuttons has android:onClick=chooseButton but for obvious reason it can't find this method...
Any ideas regarding this problem?
EDIT:
the two files doesn't seem to be linked because in the xml android:onClick="chooseButton" the IDE says: "cannot resolve symbol chooseButton"
XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/dial_view_id"
android:layout_width="match_parent"
tools:context=".DialView"
android:orientation="vertical"
android:layout_height="match_parent">
<com.package.CustomView
android:id="#+id/drawingview"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="1">
<ImageButton
android:id="#+id/button1"
android:onClick="chooseButton"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:scaleType="fitCenter"
android:background="#drawable/ic_dialpad_1_blue" />
<ImageButton
android:id="#+id/button2"
android:onClick="chooseButton"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="#drawable/ic_dialpad_2_blue"
------code repeated below-----/>
CustomView:
public class CustomView extends LinearLayout {
private String mExampleString;
private int mExampleColor = Color.RED;
private float mExampleDimension = 0;
private Drawable mExampleDrawable;
private TextPaint mTextPaint;
private float mTextWidth;
private float mTextHeight;
private ImageButton button_0, button_1, button_2, button_3, button_4, button_5, button_6;
private ImageButton button_7, button_8, button_9, button_star, button_pound;
private boolean clicked = false;
private SparseIntArray drawables = new SparseIntArray();
public DialView(Context context) {
super(context);
}
public DialView(Context context, AttributeSet attrs) {
super(context, attrs);
init(attrs, 0);
}
public DialView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(attrs, defStyle);
}
private void init(AttributeSet attrs, int defStyle) {
// Load attributes
final TypedArray a = getContext().obtainStyledAttributes(
attrs, R.styleable.DialView, defStyle, 0);
mExampleString = a.getString(
R.styleable.DialView_exampleString);
mExampleColor = a.getColor(
R.styleable.DialView_exampleColor,
mExampleColor);
// Use getDimensionPixelSize or getDimensionPixelOffset when dealing with
// values that should fall on pixel boundaries.
mExampleDimension = a.getDimension(
R.styleable.DialView_exampleDimension,
mExampleDimension);
if (a.hasValue(R.styleable.DialView_exampleDrawable)) {
mExampleDrawable = a.getDrawable(
R.styleable.DialView_exampleDrawable);
mExampleDrawable.setCallback(this);
}
a.recycle();
// Set up a default TextPaint object
mTextPaint = new TextPaint();
mTextPaint.setFlags(Paint.ANTI_ALIAS_FLAG);
mTextPaint.setTextAlign(Paint.Align.LEFT);
// Update TextPaint and text measurements from attributes
invalidateTextPaintAndMeasurements();
}
private void invalidateTextPaintAndMeasurements() {
mTextPaint.setTextSize(mExampleDimension);
mTextPaint.setColor(mExampleColor);
mTextWidth = mTextPaint.measureText(mExampleString);
Paint.FontMetrics fontMetrics = mTextPaint.getFontMetrics();
mTextHeight = fontMetrics.bottom;
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
}
public void getButtons(){}
public void chooseButton(View v){}
public void switchBackground(ImageButton button){}
}

how to put a custom view into a custom list view for list fragment

I am having a custom layout for the list fragment. Inside that custom list layout, i want to put another custom view (which do drawing things). So my question is: how to add another view to convertView in method getView().
Here is my getView method:
private class TrainingAdapter extends ArrayAdapter<Product>
{
public TrainingAdapter(ArrayList<Product> list) {
super(getActivity(), 0, list);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null)
{
convertView = getActivity().getLayoutInflater().inflate(R.layout.trainings_custom_layer_listfragment, null);
}
Product p = getItem(position);
//references to text view and image view goes here
//begin to work with custom view
StarView sv = (StarView) convertView.findViewById(R.id.star_view);
return convertView; }
Here is my layout:
<ImageView android:id="#+id/imageview_product_category"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="mini photo" />
<TextView android:id="#+id/textview_training_title"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_toRightOf="#id/imageview_product_category"
android:textColor="#color/text_color_white" />
<TextView android:id="#+id/textview_training_location"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_toRightOf="#id/imageview_product_category"
android:layout_below="#id/textview_training_title"
android:textColor="#color/text_color_white" />
<TextView android:id="#+id/textview_training_datetime"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_toRightOf="#id/imageview_product_category"
android:layout_below="#id/textview_training_location"
android:textColor="#color/text_color_white" />
<TextView android:id="#+id/textview_training_cost"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_toRightOf="#id/imageview_product_category"
android:layout_below="#id/textview_training_datetime"
android:textColor="#color/text_color_white" />
<TextView android:id="#+id/textview_training_registrationenddate"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_toRightOf="#id/imageview_product_category"
android:layout_below="#id/textview_training_cost"
android:textColor="#color/text_color_white" />
<jacky.practice.view_custom.StarView
android:id="#+id/star_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/imageview_product_category"
android:layout_below="#id/textview_training_registrationenddate"/>
Code for custom view:
public class StarView extends View {
private Paint myPaint;
private int mLevel = 0;
public StarView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
public StarView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public StarView(Context context) {
super(context);
init();
}
private void init()
{
myPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
myPaint.setColor(Color.GREEN);
}
public void setExpensive(int level)
{
mLevel = level;
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if(mLevel <= 3)
{
canvas.drawCircle(20, 20, 8, myPaint);
}
else if((mLevel > 3) && (mLevel <= 5))
{
canvas.drawCircle(20, 20, 8, myPaint);
canvas.drawCircle(40, 20, 8, myPaint);
}
else
{
canvas.drawCircle(20, 20, 8, myPaint);
canvas.drawCircle(40, 20, 8, myPaint);
canvas.drawCircle(60, 20, 8, myPaint);
}
canvas.restore();
}
}
Have you forgotten to implement onCreateView?
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.main, null);
return view;
}

Categories

Resources