代码之家  ›  专栏  ›  技术社区  ›  monoceres

xml布局中的自定义视图

  •  14
  • monoceres  · 技术社区  · 14 年前

    我通过创建SurfaceView类的子类创建了自己的视图。

    但是,我不知道如何从xml布局文件中添加它。我当前的main.xml如下所示:

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        >
    
    <View
        class="com.chainparticles.ChainView"
      android:layout_width="fill_parent"
      android:layout_height="fill_parent" 
        />
    
    
    </LinearLayout>
    

    我错过了什么?

    编辑

    更多信息

    package com.chainparticles;
    public class ChainView extends SurfaceView implements SurfaceHolder.Callback {
        public ChainView(Context context) {
            super(context);
            getHolder().addCallback(this);
        }
    // Other stuff
    }
    

    它的工作原理如下:

    ChainView cview = new ChainView(this);
    setContentView(cview);
    

    2 回复  |  直到 14 年前
        1
  •  18
  •   Rich Schuler    14 年前

    你想要:

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
    >
    
        <com.chainparticles.ChainView
          android:layout_width="fill_parent"
          android:layout_height="fill_parent" 
         />
    </LinearLayout>
    

    编辑:

    在看到剩下的代码后,它可能会抛出,因为你不能调用 getHolder 在构造器中充气。把它移到 View#onFinishInflate

    @Override
    protected void onFinishInflate() {
        getHolder().addCallback(this);
    }
    

    如果这不起作用,试着把它放在一个init函数中,然后在 Activity setContentView

    它以前可能工作过,因为从xml中膨胀构造函数时: View(Context, AttributeSet) View(Context) .

        2
  •  11
  •   nonsleepr    13 年前

    因此,如果要在XML中使用内部类,应该这样编写:

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
    >
    
        <view
          class="com.chainparticles.Foo$InnerClassChainView"
          android:layout_width="fill_parent"
          android:layout_height="fill_parent" 
         />
    </LinearLayout>
    

    看法 看法