android - 在 View 上添加按钮

标签 android xml xamarin

我有以下 axml。

<LinearLayout
   android:layout_width="wrap_content"
   android:layout_height="360dp"
   android:id="@+id/viewA">
   <View
       android:layout_width="wrap_content"
       android:layout_height="360dp"
       android:id="@+id/viewB" />
</LinearLayout>

我想以编程方式在 ViewB 上添加一个按钮。我无法弄清楚,因为 View 没有 addView 方法。

最佳答案

使用 FrameLayout 而不是 View。 View 没有 child 。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/viewA"
    android:layout_width="wrap_content"
    android:layout_height="360dp">

    <FrameLayout
        android:id="@+id/viewB"
        android:layout_width="wrap_content"
        android:layout_height="360dp" />
</LinearLayout>

只需添加您的代码:

    Button button = new Button(this);
    button.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT));
    FrameLayout group = (FrameLayout) findViewById(R.id.viewB);
    group.addView(button);

关于android - 在 View 上添加按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31735115/

相关文章:

xamarin - 减少 AppStore 应用程序大小 : Remove System. Xml?

MainAcitivity setOnClickListener 中的 java.lang.NullPointerException

android - 在 Android 库 aar 中包含外部模块

Android获取 Activity 警报列表

android - 解析 XML 时出错 : Mismatched tag - Android strange error

xml - XSLT 函数插入前无法识别

android - Android 库 (jar/aar) 可以在 Xamarin 中用于 iOS 吗

android - 如何在 onSaveInstanceState 中查看 Bundle 对象的大小?

ios - Storyboard冲突 iOS 后 XML 标记不匹配

android - 如何从我们在 xamarin.forms 中的应用程序打开设置?