【问题标题】:Placing a Drawable object in a view on a layout in an Android fragment将 Drawable 对象放置在 Android 片段中布局的视图中
【发布时间】:2012-08-01 14:02:42
【问题描述】:

我认为标题涵盖了它:) 我有一个可绘制的对象,它可以获取 .png 照片,我可以用手势操作它。我还有一个带有背景图像的 xml 布局,它应该位于这个可绘制对象的后面。一切都发生在一个片段中。

当我运行代码并到达这个片段时,会显示 png 并且手势可以工作,但是,没有膨胀的布局和后退按钮按下应用程序崩溃(我猜那是因为我在片段中使用 setContentView所以没有后栈?如何避免这种情况?)。

稍后我会将其他图层添加到场景中。

我的问题是,我怎样才能同时使用 xml 布局来膨胀片段,在其上显示可绘制对象,以及稍后在所有这些之上添加其他视图?

此片段的代码如下:

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;

}}

谢谢!

【问题讨论】:

    标签: android containers drawable inflate viewgroup


    【解决方案1】:

    我通过在该片段的 LinearLayout 包装器中添加一个 ID 来解决它,然后在使用其 xml 膨胀片段后使用 addView(view) 在其中添加一个可绘制视图的实例。

    片段 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>
    

    片段代码:

        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;
    

    【讨论】:

      猜你喜欢
      • 2016-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多