簡體   English   中英

Android-使用swipeview在片段之間發送數據

[英]Android - Sending data from fragment to fragment using swipeview

可能這是騙子,但我一直在尋找解決方案,而且它們總是與我的問題略有不同。

所以:我目前正在創建一個具有2個可滑動片段的應用程序。 TaskGroupFragment顯示一個列表,當您單擊某個項目時,它將滑到TasksFragment並顯示一個子列表。 我現在要做的是將所選項目的ID從組發送到任務,以便可以從SQLite中獲取子列表。

我知道我應該通過連接的MainActivity進行通信,現在我已經在TaskGroupsFragment中創建了一個接口並在活動中實現了這一點。 經過測試,活動收到TaskGroupID。

我遇到的問題是在TasksFragment中獲取此信息。 特別是使用swipeview會使此操作變得更加困難。

我的代碼:

MainPagerAdapter:

public class MainPagerAdapter extends FragmentStatePagerAdapter {

    public MainPagerAdapter(FragmentManager fm) {
    super(fm);
    }

    @Override
    public Fragment getItem(int i) {
        switch (i) {
            case 0: return TaskGroupFragment.newInstance();
            case 1: return TasksFragment.newInstance();
            default: return TaskGroupFragment.newInstance();
        }
    }

    @Override
    public int getCount() {
        return 2;
    }
}

TaskGroupActivity(發送片段):

    public class TaskGroupFragment extends ListFragment {

    private DoItDataSource dataSource;
    private List<TaskGroups> groups;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_task_group, container, false);

        dataSource = new DoItDataSource(getActivity());

        dataSource.open();
        JSONContainer jsonContainer = dataSource.sqliteToContainer();
        dataSource.close();

        groups = jsonContainer.getTask_groups();

        TaskGroupAdapter adapter = new TaskGroupAdapter(getActivity(), groups);
        setListAdapter(adapter);

        return view;
    }

    public static TaskGroupFragment newInstance() {
        TaskGroupFragment tgf = new TaskGroupFragment();
        return tgf;
    }

    public interface OnTaskGroupSelectedListener {
        public void onTaskGroupSelected(String taskGroupId);
    }

    OnTaskGroupSelectedListener mListener;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (OnTaskGroupSelectedListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " Interface not implemented in activity");
        }
    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {

        ((MainActivity)getActivity()).setCurrentItem(1, true);
        mListener.onTaskGroupSelected(groups.get(position).getId());
    }
}

主要活動:

public class MainActivity extends FragmentActivity  implements
        TaskGroupFragment.OnTaskGroupSelectedListener{
    private SharedPreferences savedValues;
    private DoItDataSource dataSource = new DoItDataSource(this);

    private String identifier, user, domain;

    private JSONContainer containerToday;
    private JSONContainer containerTomorrow;

    public ViewPager pager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        savedValues = getSharedPreferences("SavedValues", MODE_PRIVATE);
        identifier = savedValues.getString("Identifier", "");

        pager = (ViewPager) findViewById(R.id.activity_main_pager);
        pager.setAdapter(new MainPagerAdapter(getSupportFragmentManager()));

        if (identifier == null || identifier.equals("")) {
            Intent intent = new Intent(MainActivity.this, LoginActivity.class);
            intent.putExtra("APP_ID", APP_ID);
            startActivity(intent);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        identifier = savedValues.getString("Identifier", "");
        user = savedValues.getString("User", "");
        domain = savedValues.getString("Domain", "");
        boolean onBackPressed = savedValues.getBoolean("OnBackPressed", false);

        //
        // getting lists
        //
    }

    private void resultHandling(String json, String day) {
        if (day.equals("today")) {
            Gson gson = new Gson();
            containerToday = gson.fromJson(json, JSONContainer.class);
            jsonToSQLite(containerToday, "Today");


        } else if (day.equals("tomorrow")) {
            Gson gson = new Gson();
            containerTomorrow= gson.fromJson(json, JSONContainer.class);
            jsonToSQLite(containerTomorrow, "Tomorrow");
        }
    }

    String taskGroupId = "";

    @Override
    public void onTaskGroupSelected(String taskGroupId) {
        this.taskGroupId = taskGroupId;


    // Enter missing link here?

    }
}

TaskFragment(接收片段):

public class TasksFragment extends ListFragment
        implements OnClickListener {
    private final static String TAG = "TaskItemFragment logging";

    private DoItDataSource dataSource;
    private List<Tasks> tasks;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_task_item, container, false);

        Button backButton = (Button) 
                view.findViewById(R.id.fragment_task_item_bar_back_button);

        dataSource = new DoItDataSource(getActivity());

        dataSource.open();
        tasks = dataSource.getTasks("204"); // 204 is a placeholder, TaskGroupId should be here
        dataSource.close();

        TasksAdapter adapter = new TasksAdapter(getActivity(), tasks);
        setListAdapter(adapter);

        backButton.setOnClickListener(this);

        return view;
    }

    public static TasksFragment newInstance() {
        TasksFragment tif = new TasksFragment();
        return tif;
    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        Toast.makeText(getActivity(), "Clicked item " + position, Toast.LENGTH_LONG).show();
    }

    @Override
    public void onClick(View v) {
        switch(v.getId()) {
            case R.id.fragment_task_item_bar_back_button:
                ((MainActivity)getActivity()).setCurrentItem(0, true);
                break;
        }
    }
}

感謝Alireza! 我必須對他建議的代碼進行幾處更改,但最終它幫助我找到了解決方案!

MainPageAdapter:

public class MainPagerAdapter extends FragmentStatePagerAdapter {
    // ADDED
    private String taskGroupId;

    public MainPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int i) {
        switch (i) {
            case 0: return TaskGroupFragment.newInstance();
            // MODIFIED
            case 1:
                Bundle args = new Bundle();
                logcat("before setBundle " + taskGroupId);
                args.putString("taskGroupId",taskGroupId);
                Fragment fragment  =  new TasksFragment();
                fragment.setArguments(args);
                return fragment;
            default: return TaskGroupFragment.newInstance();
        }
    }

    // ADDED
    public void setTaskGroupId(String id){
        this.taskGroupId = id;
    }

    @Override
    public int getCount() {
        return 2;
    }
}

主要活動:

public class MainActivity extends FragmentActivity  implements
        TaskGroupFragment.OnTaskGroupSelectedListener{
    private SharedPreferences savedValues;

    private DoItDataSource dataSource = new DoItDataSource(this);

    private String identifier, user, domain;

    private JSONContainer containerToday;
    private JSONContainer containerTomorrow;

    // ADDED
    private MainPagerAdapter adapter;

    public ViewPager pager;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            savedValues = getSharedPreferences("SavedValues", MODE_PRIVATE);
            identifier = savedValues.getString("Identifier", "");

            // ADDED
            adapter = new MainPagerAdapter(getSupportFragmentManager());

            pager = (ViewPager) findViewById(R.id.activity_main_pager);
            // MODIFIED
            pager.setAdapter(adapter);

            if (identifier == null || identifier.equals("")) {
                Intent intent = new Intent(MainActivity.this, LoginActivity.class);
            intent.putExtra("APP_ID", APP_ID);
            startActivity(intent);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        identifier = savedValues.getString("Identifier", "");
        user = savedValues.getString("User", "");
        domain = savedValues.getString("Domain", "");
        boolean onBackPressed = savedValues.getBoolean("OnBackPressed", false);

        //
        // Getting lists
        //
    }


    String taskGroupId = "";

    @Override
    public void onTaskGroupSelected(String taskGroupId) {
        this.taskGroupId = taskGroupId;

        // ADDED
        adapter.setTaskGroupId(taskGroupId);
        pager.setAdapter(adapter);
        pager.setCurrentItem(1);
    }
}

TaskFragment(接收片段):

public class TasksFragment extends ListFragment implements OnClickListener {
    private final static String TAG = "TaskItemFragment logging";

    private DoItDataSource dataSource;
    private List<Tasks> tasks;

    private String taskGroupId;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_task_item, container, false);

        Button backButton = (Button) view.findViewById(R.id.fragment_task_item_bar_back_button);

        dataSource = new DoItDataSource(getActivity());

        // ADDED
        Bundle bundle = getArguments();
        taskGroupId = bundle.getString("taskGroupId");

        // MODIFIED
        dataSource.open();
        tasks = dataSource.getTasks(taskGroupId);
        dataSource.close();

        TasksAdapter adapter = new TasksAdapter(getActivity(), tasks);
        setListAdapter(adapter);

        backButton.setOnClickListener(this);

        return view;
    }

    // CAN BE REMOVED?
    //public static TasksFragment newInstance() {
    //    TasksFragment tif = new TasksFragment();
    //    return tif;
    //}

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        Toast.makeText(getActivity(), "Clicked item " + position, Toast.LENGTH_LONG).show();
    }

    @Override
    public void onClick(View v) {
        switch(v.getId()) {
            case R.id.fragment_task_item_bar_back_button:
                ((MainActivity)getActivity()).setCurrentItem(0, true);
                break;
        }
    }
}

請注意,我使用taskGroupId作為字符串,而不是整數。

首先,您需要確保適配器知道taskGroupID。 只需在您的適配器中添加一個變量和一個公共方法。

public class MainPagerAdapter extends FragmentStatePagerAdapter {
private int taskGroupId;


public void setTaskGroupId(int id){
   this.taskGroupId = id;
}
}

然后在您的活動中存儲對適配器的引用。 現在,只要GroupId更改,只需調用此方法

    @Override
public void onTaskGroupSelected(String taskGroupId) {
    this.taskGroupId = taskGroupId;
    adapter.setTastGroupId = taskGroupId; //data needed to initialize fragment. 
    adapter.setCurrentItem(1); //going to TasksFragment page

}

那么您需要在開始片段之前放入一些浮石。

    @Override
    public Fragment getItem(int i) {
        //this code is only for case 1:
        Bundle args = new Bundle();
        args.putInt("taskGroupId",taskGroupId);
        Fragment fragment =  new TasksFragment();
        fragment.setArguments(args);
        return fragment;
    }

最后使用TaskFragment中的數據顯示正確的內容。

暫無
暫無

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

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