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