如何在DialogFragment中使用Activity的方法?

时间:2015-08-28 08:07:05

标签: c# android xamarin

我是C#编程和Android开发的新手。 我正在尝试构建应用程序并需要帮助。这是我的对话框片段类,我希望使用另一个Activity(Member_Activity)中的方法(其名为country_set)

public class Search_Dialog: DialogFragment
{
    private EditText mName,mFathersName;

    private Member_Activity activity;
    private Button mSearchButton;
    private ArrayAdapter mCountryListAdapter;
    private AutoCompleteTextView mCountry;
    private List<string> mList;


    public event EventHandler<SearchEventArgs> searchDialogFilled;
    public override Android.Views.View OnCreateView (Android.Views.LayoutInflater inflater, Android.Views.ViewGroup container, Android.OS.Bundle savedInstanceState)
    {
        var view=inflater.Inflate (Resource.Layout.Dialog_Search, container, false);
        activity = new Member_Activity ();
        mName = view.FindViewById<EditText> (Resource.Id.Name);
        mFathersName = view.FindViewById<EditText> (Resource.Id.FathersName);
        mCountry = view.FindViewById<AutoCompleteTextView> (Resource.Id.Country);
        mSearchButton = view.FindViewById<Button> (Resource.Id.SearchBtn);

        return view;

    }

    void MSearchButton_Click (object sender, EventArgs e)
    {
        searchDialogFilled.Invoke (this, new SearchEventArgs (mName.Text, mFathersName.Text, "", "", "", "", "", "", "",""));
        this.Dismiss();
    }
    public override void OnActivityCreated (Bundle savedInstanceState)
    {
        Dialog.Window.RequestFeature (WindowFeatures.NoTitle);

        base.OnActivityCreated (savedInstanceState);
        mList = activity.country_set ();
        mCountryListAdapter = new ArrayAdapter (this.Activity, Android.Resource.Layout.SimpleDropDownItem1Line, mList);
        mCountry.Adapter = mCountryListAdapter;
    }        
}

public class Member_Activity : Activity
{
    public List<string> country_set()   
    {
        mCountryUrl = new Uri ("http://theredcatalyst.com/jain-samaj/restservice/country");
        mList = new List<string> ();
        mCountry = new List<Country> ();
        adapter = new ArrayAdapter (this, Android.Resource.Layout.SimpleSpinnerItem);
        WebClient client = new WebClient ();
        client.DownloadDataAsync (mCountryUrl);
        client.DownloadDataCompleted += (sender, e) => {
          RunOnUiThread (() => {
           string json = Encoding.UTF8.GetString (e.Result);
           mCountry = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Country>> (json);
           var mList = mCountry.Select(c=>c.name).ToList();

          });

       }; 
       return mList;
    }
}

请帮帮我。我该怎么做呢?

1 个答案:

答案 0 :(得分:1)

通过在片段Member_Activity内手动创建OnCreate,可以绕过设置活动的正常方式,从而使其处于无效状态。

提供Search_Fragment始终归Member_Activity所有,您可以通过投放片段Activity属性来访问引用:

activity = base.Activity as Member_Activity;