android - 将 Drawable 对象放置在 Android fragment 中布局的 View 中

标签 android containers drawable inflate viewgroup

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

当我运行代码并到达此 fragment 时,会显示 png 并且手势有效,但是,没有膨胀的布局并且按下后退按钮时应用程序崩溃(我猜这是因为我在 fragment 中使用了 setContentView所以没有返回堆栈?我该如何避免这种情况?)。

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

我的问题是,我怎样才能用 xml 布局扩充 fragment ,在它上面显示可绘制对象,然后可能在所有这些之上添加其他 View ?

此 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;

}}

谢谢!

最佳答案

我通过在这个 fragment 的 LinearLayout 包装器中添加一个 ID 解决了这个问题,然后在用它的 xml 膨胀 fragment 后用 addView(view) 在其中添加一个可绘制 View 的实例。

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>

fragment 代码:

    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;

关于android - 将 Drawable 对象放置在 Android fragment 中布局的 View 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11760995/

相关文章:

android - 从 react-native-static-server : undefined is not an object (evaluating 'this.staticServer.start' ) 启动 StaticServer 时出错

c# - 颜色按钮 C# Xamarin Android

docker - 使Docker容器保持事件状态并运行Java应用程序

linux - 容器进程如何附加到 docker 中的 containerd-shim

android - 可在字符串资源中绘制

android - 在 Android 5.0 Lollipop 上以编程方式在 View 上设置主题

android - (MPAndroidChart) 一些标签没有显示在条形图中

c++ - 进行少量插入时应该使用哪个 STL 容器?

android - 如何在 Java Android 中的可绘制对象上设置白色滤镜

缩放按钮的Android自定义形状