Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/220.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 如何在xml文件上显示自定义视图?_Android - Fatal编程技术网

Android 如何在xml文件上显示自定义视图?

Android 如何在xml文件上显示自定义视图?,android,Android,如上图所示,类视图在MainActivity中声明,因此它没有XML文件。我想在自定义视图上添加一个按钮并对其进行操作 如果类视图位于不扩展视图的java类内部,如何以xml显示自定义视图?创建xml自定义布局,为其分配一个视图。然后可以将视图添加到其他布局中。查看以了解有关创建自定义视图的详细信息我认为您无法在视图中设置任何其他视图,我认为只有像LinearLayout,RelativeLayout这样扩展ViewGroup的布局才能使用addView(View View View)添加其他视

如上图所示,类视图在MainActivity中声明,因此它没有XML文件。我想在自定义视图上添加一个按钮并对其进行操作


如果类视图位于不扩展视图的java类内部,如何以xml显示自定义视图?

创建xml自定义布局,为其分配一个视图。然后可以将视图添加到其他布局中。查看以了解有关创建自定义视图的详细信息

我认为您无法在视图中设置任何其他视图,我认为只有像
LinearLayout
RelativeLayout
这样扩展
ViewGroup
的布局才能使用
addView(View View View)
添加其他视图

示例如下

您可以创建xml布局文件并将自定义视图放入其中

示例包含自定义视图的xml文件

<?xml version="1.0" encoding="utf-8"?>
<com.example.package.MyView 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>
现在,您可以任意分配和操作myView。如果仍然要添加按钮。在xml文件中创建按钮,并以编程方式膨胀或创建并将其添加到
linear.addView(视图)

// Inflate your xml view using layout inflater.
LayoutInflater inflater = getSystemService(Context.LAYOUT_INFLATER_SERVICE);

View myView = (MyView) inflater.inflate(R.layout.example, null);

// now create a container class or map any of it from main_activity.xml layout.
LinearLayout linear = new LinearLayout(this);

/* LinearLayout linear = (LinearLayout) findViewById(R.layout.myLayout); */

// if you have created it programatically, set its width and height as following
linear.setLayoutParams(new ViewGroup.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,    // width
            ViewGroup.LayoutParams.MATCH_PARENT));  // height

// else mention it in layout xml file.

linear.removeAllViews(); // clear layout before setting new one.

linear.addView(myView); // set custom view inside layout.