将视图从单独的布局文件添加到水平滚动视图

本文关键字:视图 添加 滚动 文件 水平 布局 单独 | 更新日期: 2023-09-27 18:29:06

我正在尝试将卡片列表添加到滚动视图中,使用一个单独的xml文件作为布局。

然而,在按下按钮时,我得到以下错误:

System.NullReferenceException: Object reference not set to an instance of an object

我可以在不使用Card.xml布局的情况下很好地添加文本,当我将其用作布局时,我会收到错误。

protected override void OnCreate(Bundle bundle)
{
    base.OnCreate(bundle);
    // Set our view from the "main" layout resource
    SetContentView(Resource.Layout.Main);

    Button buttonWhite = FindViewById<Button>(Resource.Id.button2);

    //On button click, loop though dealt hand of cards and add each to Scrollveiw using Card layout file
    buttonWhite.Click += delegate
    {
        HorizontalScrollView ScrollView = (HorizontalScrollView)FindViewById(Resource.Id.horizontalScrollView1);
        //create layout from Cardlayout file
        LinearLayout Test_card = (LinearLayout)FindViewById(Resource.Layout.Card);
        //loopthough Players hand and use text to add to card layout then add layout with text to scrollview
        foreach (Card Test in p.hand)
        {

            //create new textview
            TextView Test_Text = new TextView(this);

            //set new textviews text value to card text
            Test_Text.Text = Test.text;
            //addview to layout
            Test_card.AddView(Test_Text);
        }
        //add layout to scrollview
        ScrollView.AddView(Test_card);

    };
}

将视图从单独的布局文件添加到水平滚动视图

您应该扩展Card资源布局,它不在您当前的上下文中。所以你应该更换:

 LinearLayout Test_card = (LinearLayout)FindViewById(Resource.Layout.Card);

使用(Java):

LinearLayout Test_card = (LinearLayout) getLayoutInflater().inflate(Resource.Layout.Card);

C#(可能):

LinearLayout Test_card = (LinearLayout) this.LayoutInflater.Inflate(
                Resource.Layout.Card ...);