繁体   English   中英

如何结合布局和视图?

[英]How to combine a layout and a view?

我正在用Android Studio制作2D Android游戏,我有一个activity_customer.xml文件,我有一个MyView a但是当我这样使用时,在屏幕上看不到MyView a ,但在屏幕上却看到activity_customer.xml

Customer.java:

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        MyView a = new MyView(this);
        setContentView(a);
        setContentView(R.layout.activity_customer);
}

但是,如果我这样使用,则在屏幕上可以看到MyView a ,但在屏幕上却看不到activity_customer.xml

 Customer.java:

 protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        MyView a = new MyView(this);
        setContentView(R.layout.activity_customer);
        setContentView(a);

}

所以我想同时看到MyView aactivity_customer.xml ,如何将它们组合在一个屏幕中?

这是我的activity_customer.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.asdf.catchtheball.main">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:text="Button" />
</RelativeLayout>

如果您创建了自己的视图类,则可以将其添加到活动视图中,如下所示:

RelativeLayout mainLayout = (RelativeLayout)findViewById(R.id.relativeLayout); //Your main element at activity's xml file
mainLayout.addView(yourView); // replace your 'a' object with 'yourView'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM