Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Placing a Drawable object in a view on a layout in an Android fragment

I think the title covers it :) I have a drawable object that fetches .png photo which I can manipulate with gestures. I also have a xml layout with a background image that is supposed to be behind this drawable object. Everything happens in a fragment.

When I run the code and get to this fragment, png is displayed and gestures work, BUT, there is no inflated layout and on back button press app crashes (I'm guessing that is because I'm using setContentView in fragment so there is no back stack? How do I avoid this?).

Later on I will add other layers to the scene.

My question is, how can I both inflate the fragment with xml layout, display drawable on top of it, and maybe later on add other views on top of all that?

Code goes like this for this fragment:

public class RoomFragment extends Fragment {

ViewGroup mRoot;

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

    mRoot = (ViewGroup) inflater.inflate(R.layout.room_fragment, null);

    /** Placing furniture .png element in SandboxView */
    Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
            R.drawable.furniture);
    View view = new SandboxView(this.getActivity(), bitmap);
    this.getActivity().setContentView(view); // Replace with inflater?

    return mRoot;

}}

Thank you!

like image 660
3mpetri Avatar asked Nov 04 '22 19:11

3mpetri


1 Answers

I solved it by adding an ID in LinearLayout wrapper of this fragment, and then adding an instance of drawable view in it with addView(view) after inflating fragment with its xml.

Fragment XML:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/bitmapBox"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/room"
    android:gravity="bottom|center"
    android:orientation="vertical" >
</LinearLayout>

Piece of fragments code:

    ViewGroup mRoot;

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

    mRoot = (ViewGroup) inflater.inflate(R.layout.room_fragment, null);

    /** placing furniture element in SandboxView */
    LinearLayout myLayout = (LinearLayout) mRoot
            .findViewById(R.id.bitmapBox);

    Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
            R.drawable.furniture);

    View view = new SandboxView(this.getActivity(), bitmap);

    myLayout.addView(view);

    return mRoot;
like image 153
3mpetri Avatar answered Nov 15 '22 00:11

3mpetri