Skip to main content
 首页 » 编程设计

c#之如何在 android xamarin 中动态地将按钮添加到 View

2024年08月06日29lidabo

我正在尝试使用 xamarin.android 将按钮动态添加到 droid 应用程序中的 View 。 我需要能够做到这一点,因为我将不得不在项目期间动态添加一些东西。 这是我正在尝试的代码。

public class FeedbackFragment : Android.Support.V4.App.Fragment 
{ 
    public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
    { 
        var view = inflater.Inflate (Resource.Layout.ChallengeFeedbackView, container, false); 
 
        LinearLayout parentLayoutView = view.FindViewById (Resource.Id.feedbackView);//LinearLayout 
        ScrollView feedbackscrollView = parentLayoutView.FindViewById (Resource.Id.scrollView1);//ScrolView 
 
        var scrollviewInnerContainerView = feedbackscrollView.FindViewById (Resource.Id.scrollViewInnerContainer); 
        scrollviewInnerContainerView.SetBackgroundColor (Android.Graphics.Color.White);//Linear Layout 
 
        var silhouteeContainer = scrollviewInnerContainerView.FindViewById (Resource.Id.view1);//View 
 
        Button b1 = new Button (this); 
        b1.SetText ("Click Me"); 
 
        LinearLayout.LayoutParams prm = new LinearLayout.LayoutParams (LinearLayout.LayoutParams.MatchParent,LinearLayout.LayoutParams.MatchParent); 
 
     // I want to achieve something like this 
       silhouteeContainer.AddView(b1); //when i actually do this , it shows an error. 
 
        return view; 
    } 
} 

下面是 fChallengeFeedbackView.axml 的样子。

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/feedbackView" 
    android:orientation="vertical" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"> 
    <ScrollView 
        android:layout_width="match_parent" 
        android:layout_height="wrap_content" 
        android:id="@+id/scrollView1"> 
        <LinearLayout 
            android:orientation="vertical" 
            android:layout_width="fill_parent" 
            android:layout_height="fill_parent" 
            android:id="@+id/scrollViewInnerContainer"> 
            <View 
                android:layout_width="fill_parent" 
                android:layout_height="275dp" 
                android:id="@+id/view1" 
                android:background="#00ff00" /> 
            <View 
                android:layout_width="fill_parent" 
                android:layout_height="275dp" 
                android:id="@+id/view2" 
                android:background="#ff0000" /> 
            <View 
                android:layout_width="fill_parent" 
                android:layout_height="275dp" 
                android:id="@+id/view3" 
                android:background="#0000ff" /> 
        </LinearLayout> 
    </ScrollView> 
</LinearLayout> 

请您参考如下方法:

问题是您不能将 subview 添加到继承自 View 的内容。为此,类型必须继承自 ViewGroup。此类布局是 LinearLayout、FrameLayout 和 RelativeLayout。

因此,向 AXML 文件中声明的三个 View 实例添加元素是不可能的。