amirsoltani
amirsoltani

Reputation: 91

How to Draw Rectangle in fragment class

I've searched for this question (the title) and I've got this:

A Rect created in a view class and passed into a fragment, but unfortunately it didn't work, I don't see the rectangle in fragment 1 when i run it. what am i doing wrong, and Thank You in advance

public class Rectangle extends View {

    public Rectangle(Context context) {
        super(context);
    }
    @Override
    public void onDraw(Canvas canvas ) {
        Rect rectangle = new Rect(200, 200, 200, 200);

        Paint paint = new Paint();
        paint.setAntiAlias(true);
        paint.setColor(Color.RED);

        canvas.drawRect(rectangle, paint);

        super.onDraw(canvas);
    }
}


public class FragmentOne extends Fragment {
RelativeLayout relativeLayout;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        View myInflatedView= inflater.inflate(R.layout.fragment_one_layout,container,false);

        relativeLayout = (RelativeLayout) myInflatedView.findViewById(R.id.Frag1);
        relativeLayout.addView(new Rectangle(getActivity()));

        return myInflatedView;
    }

}

XML for fragment 1:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:id="@+id/Frag1"
android:layout_height="match_parent"
android:background="#000">


<com.redot.puzzle1.Rectangle
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    />

  </RelativeLayout>

Upvotes: 0

Views: 565

Answers (1)

KeLiuyue
KeLiuyue

Reputation: 8237

You problem is Rect rectangle = new Rect(200, 200, 200, 200);

The left-top coordinate is the same as the right-bottom coordinate .So it will not display in the layout.

Just change it in your code and try it .

Try this in your code .

public class Rectangle extends View {

public Rectangle(Context context) {
    super(context);
}

public Rectangle(Context context, @Nullable AttributeSet attrs) {
    super(context, attrs);
}

public Rectangle(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    Paint paint = new Paint();
    paint.setAntiAlias(true);
    paint.setColor(Color.RED);
    canvas.drawRect(400,200,800,600,paint);
}
}

Then

<com.redot.puzzle1.Rectangle
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

Upvotes: 2

Related Questions