簡體   English   中英

將數據從一個片段發送到xamarin.android中的另一個片段

[英]Send data from one fragment to another fragment in xamarin.android

我正在嘗試使用Xamarin.android做一個應用程序。 它是“ ToDoList”,我有兩個選項卡,其中之一是創建和編輯瑣事(稱為“撤消”)。 另一個是標記為完成的雜務(稱為完成)。 我已使用“片段”作為選項卡,而我要完成的工作是當我將一項任務標記為完成時,要從“撤消”選項卡的列表中將其刪除,然后在“完成”選項卡的列表中添加一項。

MainActivity.cs

public class MainActivity : Activity
{
    protected override void OnCreate(Bundle savedInstanceState)
    {
            base.OnCreate(savedInstanceState);
            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.activity_main);

            this.ActionBar.NavigationMode = ActionBarNavigationMode.Tabs;


            var tab1 = ActionBar.NewTab();
            tab1.SetText("Undone");
            var tabFirst = new UndoneListFragment();
            tab1.TabSelected += (sender, e) =>
            {
                var fragment = this.FragmentManager.FindFragmentById(Resource.Id.tabsContainer);

                if (fragment != null)
                    e.FragmentTransaction.Remove(fragment);

                e.FragmentTransaction.Add(Resource.Id.tabsContainer, tabFirst);
            };

            tab1.TabUnselected += (sender, e) =>
            {
                e.FragmentTransaction.Remove(tabFirst);
            };


            var tab2 = ActionBar.NewTab();
            tab2.SetText("Done");
            var tabSecond = new DoneListFragment();
            tab2.TabSelected += (sender, e) =>
            {
                var fragment = this.FragmentManager.FindFragmentById(Resource.Id.tabsContainer);

                if (fragment != null)
                    e.FragmentTransaction.Remove(fragment);

                e.FragmentTransaction.Add(Resource.Id.tabsContainer, tabSecond);
            };

            tab2.TabUnselected += (sender, e) =>
            {
                e.FragmentTransaction.Remove(tabSecond);
            };

            ActionBar.AddTab(tab1);
            ActionBar.AddTab(tab2);

      }
}  

UndoneListFragment.cs

public class UndoneListFragment : Fragment
{
    List<Task> tasks = new List<Task>();
    ListView lView;

    TasksViewAdapter adapter;
    View view;

    public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {

            // Use this to return your custom view for this Fragment
            // return inflater.Inflate(Resource.Layout.YourFragment, container, false);

            base.OnCreateView(inflater, container, savedInstanceState);

            view = inflater.Inflate(Resource.Layout.undoneListView, container, false);

            Button addBtn = view.FindViewById<Button>(Resource.Id.AddBtn);
            lView = view.FindViewById<ListView>(Resource.Id.TasksViewList);



            adapter = new TasksViewAdapter(view.Context, tasks);

            lView.Adapter = adapter;
            lView.ItemClick += Edit;

            addBtn.Click += AddTask;
            return view;
    }
}

public override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
      base.OnActivityResult(requestCode, resultCode, data);

      switch (requestCode)
      {

                case 10:
                    if (resultCode == Result.Ok)   //Edit an already existing task
                    {
                        var replacedTaskName = data.GetStringExtra("new_name" ?? "Name not found");
                        var position = data.GetIntExtra("listPos", 0);
                        bool done = data.GetBooleanExtra("done", false);

                        Task t = new Task(replacedTaskName);

                        if (done == true)
                        {
                            t.TaskStatus = Status.Done;

                             //here I want to implement the code to somehow  

                             //send the replacesTaskName to the second fragment

                            //Your suggestion is here
                            DoneListFragment frag = new DoneListFragment();
                            Bundle b = new Bundle();
                            b.PutString("MyKey",replacedTaskName);
                            frag.Arguments = b;

                        }

                        tasks[position] = t;
                        adapter.NotifyDataSetChanged();
                        string newName = tasks[position].TaskName;
                        break;
                    }
      }
}  

DoneListFragment.cs

public class DoneListFragment : Fragment
{
    List<Task> doneTasks = new List<Task>();
    ListView lView;
    TasksViewAdapter adapter;
    public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {

            base.OnCreateView(inflater, container, savedInstanceState);
            var view = inflater.Inflate(Resource.Layout.doneListView, container, false);

            Button deleteBtn = view.FindViewById<Button>(Resource.Id.DeleteAllBtn);
            lView = view.FindViewById<ListView>(Resource.Id.doneList);


            adapter = new TasksViewAdapter(view.Context, doneTasks);
            lView.Adapter = adapter;

            if(Arguments != null)
            {
                string value= Arguments.GetString("MyKey");

            }

            //click to delete done tasks
            deleteBtn.Click += DeleteAll;

            return view;
    }
}

為了從一個片段發送數據,另一個簡單的步驟是在替換片段或調用片段的同時創建構造函數。

例如:

假設我有兩個片段,

  1. ActionFragment

  2. ActionDetailsFragment

現在,我想將數據從“ ActionFragment”發送到“ ActionDetailsFragment”:

在ActionFragment中:

fragmentManager = getChildFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frameLayoutActionDetails, new ActionDetailsFragment(Data x, Data y)).commitAllowingStateLoss( );

現在下面的代碼將在“ ActionDetailsFragment”中

public class ActionDetailsFragment extends AppFragment {
Data x;
Data y;

    public ActionDetailsFragment(Data x, Data y) {
        super();
        this.x = x;
        this.y = y;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        —————————————
////———Here is your code———————
—————————————————

}

現在,您可以在ActionDetailsFragment中使用“ Data x,Data y”……就這樣……

注意:數據x和數據y都是虛數變量。

Activity不能在TabLayout或ViewPager中使用,必須使用Fragments。 您可以改用“捆綁包”,

Fragment fragment = new Fragment();
Bundle bundle = new Bundle();
bundle.putInt(key, value);
fragment.setArguments(bundle);

然后在您的片段中,使用以下方法檢索數據(例如,在onCreate()方法中):

Bundle bundle = this.getArguments();
if (bundle != null) {
        int myInt = bundle.getInt(key, defaultValue);

}

好吧,如果您正在尋找“片段到片段”數據傳輸的明智之舉,那就是使用片段參數,如下所示:

  • 在您的情況下初始化片段對象時:

     var frag= new DoneListFragment(); Bundle bundle= new Bundle(); bundle.PutString("YourKey", "YourValue"); frag.Arguments=bundle; 
  • 然后,要檢索此數據,請在OnCreateView方法的DoneListFragment中執行以下操作:

     if(Arguments!=null) { String value = Arguments.GetString("YourKey"); } 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM