在Android中绘制片段

Pet*_*ett 0 java android ondraw android-fragments

我有以下代码:

import android.app.Fragment;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.widget.TextView;

public class MainFragment extends Fragment {

protected AlphaAnimation fadeIn = new AlphaAnimation(0.0f , 1.0f ); 


public MainFragment(){}


public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.main_fragment, container, false);
    String fontPath = "fonts/roboto.ttf";
    Typeface font = Typeface.createFromAsset(getActivity().getAssets(), fontPath);

    TextView txt1 = (TextView) rootView.findViewById(R.id.headerTextView);
    txt1.setTypeface(font); 

    TextView txt2 = (TextView) rootView.findViewById(R.id.instructions);
    txt2.setTypeface(font);


    txt1.startAnimation(fadeIn);
    txt2.startAnimation(fadeIn);
    fadeIn.setDuration(1400);
    fadeIn.setFillAfter(true);

    Rect rectangle = new Rect(200, 56, 200, 112);


    return rootView;
  }
}
Run Code Online (Sandbox Code Playgroud)

我正在尝试绘制一个矩形,但对于我的生活无法理解.我到处寻找onDraw()方法,但我不相信片段中有可能.

Lib*_*bin 8

绘制Rectanglein Activity或in没有区别Fragment.您只需要View添加到您的布局.你可以随意画出任何东西.

创建一个自定义视图并覆盖onDraw()这样以创建一个矩形.

  private class Rectangle extends View{
    Paint paint = new Paint();

    public Rectangle(Context context) {
        super(context);
    }
    @Override
    public void onDraw(Canvas canvas) {
        paint.setColor(Color.GREEN);
        Rect rect = new Rect(20, 56, 200, 112);
        canvas.drawRect(rect, paint );
    }
 }
Run Code Online (Sandbox Code Playgroud)

现在将此视图添加到您的布局中,它可以是布局设置Fragment or Activity.

RelativeLayout relativeLayout = (RelativeLayout) rootView.findViewById(R.id.container);
relativeLayout.addView(new Rectangle(getActivity()));
Run Code Online (Sandbox Code Playgroud)

即,R.id.container是布局ID.