片段无法从其他片段中找到变量

时间:2019-06-10 13:52:53

标签: c# android android-fragments xamarin.android

我有问题。我有2个Android.Support.V4.App.Fragments

在第一个Framgent中,我使用以下代码:

AgentSpinnerAdapter = new ArrayAdapter<string>(Context, Android.Resource.Layout.SimpleSpinnerDropDownItem);
AgentSpinner.Adapter = AgentSpinnerAdapter;

foreach (string[] str in NamesArray)
{
    string AgentId = str[0];
    string Owner = str[1];
    string Exchange = str[2];
    string Remark = str[3];

    AgentSpinnerAdapter.Add("Agent " + AgentId + " - " + Owner + " - " + Remark);
}

在第二个片段中,我将此行称为:

dbValue = Fragment1.AgentSpinnerAdapter.GetItem(0);

但是它说AgentSpinnerAdapter是一个空引用,这很奇怪,因为它被填充了。我已将AgentSpinnerAdapter设置为Public static。同样在MainActivity中,我首先创建Fragment1,然后创建Fragment2,如下所示:

Fragment1 = Fragment1.NewInstance();            
Fragment2 = Fragment2.NewInstance();

我在做什么错了?

更新

这是完整的Fragment1.cs方法

public void LoadAgentSpinner()
{
    string json = "";

    try
    {
        string html = string.Empty;
        string url = "https://www.efy.nl/app/getagents.php";

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        IgnoreBadCertificates();
        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
        using (Stream stream = response.GetResponseStream())
        using (StreamReader reader = new StreamReader(stream))
        {
            json = reader.ReadToEnd();
        }
    }
    catch (Exception ex1)
    {
        try
        {
            WebClient client = new WebClient();
            NameValueCollection fields = new NameValueCollection();
            fields.Add("error", ex1.GetBaseException().ToString());
            string url = "https://www.mywebsite.com";
            IgnoreBadCertificates();
            byte[] respBytes = client.UploadValues(url, fields);
            string resp = client.Encoding.GetString(respBytes);

            SelectedQuantity.Text = "";
            SelectedLimit.Text = "";
        }
        catch (Exception ex2)
        {
            string exFullName = (ex2.GetType().FullName);
            string ExceptionString = (ex2.GetBaseException().ToString());
        }
    }

    //Parse json content
    var jObject = JObject.Parse(json);

    //Create Array from everything inside Node:"Coins"
    var agentPropery = jObject["Agents"] as JArray;

    //Create List to save Coin Data
    agentList = new List<agent>();

    //Find every value in Array: coinPropery
    foreach (var property in agentPropery)
    {
        //Convert every value in Array to string
        var propertyList = JsonConvert.DeserializeObject<List<agent>>(property.ToString());

        //Add all strings to List
        agentList.AddRange(propertyList);
    }

    //Get all the values from Name, and convert it to an Array
    string[][] NamesArray = agentList.OrderBy(i => i.AgentId)
        .Select(i => new string[] { i.AgentId.ToString(), i.Owner, i.Exchange, i.Remark })
        .Distinct()
        .ToArray();


    AgentSpinnerAdapter = new ArrayAdapter<string>(Context, Android.Resource.Layout.SimpleSpinnerDropDownItem);
    AgentSpinner.Adapter = AgentSpinnerAdapter;

    foreach (string[] str in NamesArray)
    {
        string AgentId = str[0];
        string Owner = str[1];
        string Exchange = str[2];
        string Remark = str[3];

        AgentSpinnerAdapter.Add("Agent " + AgentId + " - " + Owner + " - " + Remark);  // format your string here
    }

    if(MainActivity.db.CheckExistTableSettings("Default Agent") == true)
    {
        string Value = MainActivity.db.SelectValueFromTableSettings("Default Agent");
        int spinnerPosition = AgentSpinnerAdapter.GetPosition(Value);
        AgentSpinner.SetSelection(spinnerPosition);
    }
    else
    {
        AgentSpinner.SetSelection(0);
    }            
}

1 个答案:

答案 0 :(得分:1)

在我的一些应用程序中,有必要从我的主Activity中访问其他片段,因此我们执行以下操作:

public class MainActivity : AppCompatActivity, BottomNavigationView.IOnNavigationItemSelectedListener 
{
    public static Dictionary<string, Fragment> FragmentList { get; set; }
    private Fragment currentFragment = null;
    private BottomNavigationView navigation;

    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        SetContentView(Resource.Layout.layout_mainactivity);

        // create our fragments and initialise them early.
        if (FragmentList == null)
        {
            FragmentList = new Dictionary<string, Fragment>
            {
                { "main", MainFragment.NewInstance() },
                { "bugreport", BugReportFragment.NewInstance() },
                { "settings", SettingsFragment.NewInstance() }
            };
        }

        navigation = FindViewById<BottomNavigationView>(Resource.Id.bottom_nav);
        navigation.SetOnNavigationItemSelectedListener(this);
        navigation.SelectedItemId = Resource.Id.navigation_main;
    }

     public bool OnNavigationItemSelected(IMenuItem item)
    {
        if (!popAction)
        {
            navigationResourceStack.Push(item.ItemId);
        }

        switch (item.ItemId)
        {
            case Resource.Id.navigation_main:
                currentFragment = FragmentList["main"];
                break;
            case Resource.Id.navigation_settings:
                currentFragment = FragmentList["settings"];
                break;
            case Resource.Id.navigation_bugreport:
                currentFragment = FragmentList["bugreport"];
                break;
        }

        if (currentFragment == null)
        {
            return false;
        }
        else
        {
            FragmentManager.BeginTransaction().Replace(Resource.Id.frame_content, currentFragment).Commit();
            return true;
        }
    }   
}

这意味着您可以执行MainActivity.FragmentList [“ main”]之类的操作,然后在实际初始化的类上调用任何公共方法,因为指向该类的指针存储在字典中。