How to Draw in fragment?

心已入冬 提交于 2019-12-05 21:29:32
Kanak Sony

There is nothing special with fragment here.

Code written in Fragment -

public class DrawFragment extends Fragment {
    DrawView  drawView;

    public DrawFragment() {
    }

    /**
     * Returns Instance of DrawFragment
     * 
     * @return Instance of DrawFragment
     */
    public static DrawFragment getInstance() {
        DrawFragment fragment = new DrawFragment();
        fragment.setRetainInstance(true);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View _view = inflater.inflate(R.layout.layout_drawing_fragment,
                container, false);
        //lets keep a reference of DrawView 
        drawView = (DrawView ) _view.findViewById(R.id.drawing);
        return _view;
    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}

Code of Activity onCreateView() only-

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_base_activity);
        // set Draw Fragment
        mFragmentManager = getFragmentManager();
        mFragmentTransaction = mFragmentManager.beginTransaction();
        mDrawFragment = DrawFragment.getInstance();
        mFragmentTransaction.add(R.id.frame_drawing, mDrawFragment, "draw");
        mFragmentTransaction.commit();
    }

Layout of Fragment -

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/parent"
    android:layout_width="fill_parent"
    android:layout_height="match_parent" >

    <com.app.widgets.DrawView 
        android:id="@+id/drawing"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_marginBottom="3dp"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:layout_marginTop="3dp"
        android:background="@android:color/transparent" >
    </com.app.widgets.DrawView>

</RelativeLayout>

EDIT: Check following links for drawing lines on Canvas -

Android Canvas drawLine

How to draw a line in android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!