如何在片段类中绘制矩形

时间:2017-09-19 01:25:25

标签: android android-fragments

我已经搜索了这个问题(标题)并且我已经得到了这个:

在视图类中创建并传递到片段中的Rect,但不幸的是它没有工作,当我运行它时,我看不到片段1中的矩形。 我做错了什么,并提前谢谢你

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;
    }

}

片段1的XML:

<?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>

1 个答案:

答案 0 :(得分:2)

您的问题是Rect rectangle = new Rect(200, 200, 200, 200);

左上角坐标与右下角坐标相同。因此它不会显示在布局中。

只需在代码中进行更改即可尝试。

在您的代码中尝试此操作。

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);
}
}

然后

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