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

时间:2016-01-05 17:22:01

标签: c# android xamarin-studio

我正在尝试将一个卡片列表添加到滚动视图中,使用一个单独的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);


    };
}

1 个答案:

答案 0 :(得分:0)

您应该充值卡资源布局,它不在您当前的上下文中。所以你应该替换:

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

with(Java):

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

C#(也许):

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