【问题标题】:Add view to Horizontal Scroll View from separate layout file从单独的布局文件将视图添加到水平滚动视图
【发布时间】:2016-01-05 17:22:00
【问题描述】:

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


    };
}

【问题讨论】:

    标签: c# android xamarin-studio


    【解决方案1】:

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

     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 ...);
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-24
    • 1970-01-01
    • 1970-01-01
    • 2011-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多