我有以下代码:
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;
}
}
我试图绘制一个矩形,但是对于我的生活却无法弄明白。我到处寻找onDraw()方法,但我不相信片段中有可能。
答案 0 :(得分:8)
在Rectangle
或Activity
中绘制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 );
}
}
现在将此视图添加到您的布局中,它可以是Fragment or Activity
中设置的布局。
RelativeLayout relativeLayout = (RelativeLayout) rootView.findViewById(R.id.container);
relativeLayout.addView(new Rectangle(getActivity()));
即,R.id.container是布局ID。
答案 1 :(得分:0)
创建自己的RelativeLayout
类,在本例中为MyRelativeLayout
(扩展了RelativeLayout类)。
然后实施onDraw
功能并添加你的方格。
在Fragment
的{{1}}方法中,返回onCreateView
。
阅读评论。
MyRelativeLayout