在我的视图子类中使用 xml 文件



>我有一个创建视图子对象的活动类

public class DaDActivity extends Activity {
   /** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(new DragSurface(this));
   }
}

这是我的拖拽表面.java

public class DragSurface extends View{
   public DragSurface(Context context) {
        super(context);
        setFocusable(true);
   }
}

我也有 dragsurface.xml 文件,但我不知道如何在我的 DragSurface 中使用这个 xml 文件.java.我的意思是我希望 DragSurface.java 在 dragsurface 中使用背景、按钮或类似的东西.xml但我无法.java链接到.xml

感谢您的帮助..

LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view  = inflater.inflate(R.layout.yourlayout,null);

尝试上面的行来膨胀您的 XML 文件。尝试以下代码

:::
public class DaDActivity extends Activity {
   /** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(new DragSurface(this).createView());
   }
}

这是我的拖拽表面.java

public class DragSurface extends View{
   public DragSurface(Context context) {
        super(context);
        setFocusable(true);
   }
   public View createView(){
        LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view  = inflater.inflate(R.layout.yourlayout,null);
        return view; 
     }
}

最新更新