将变量从MainActivity传递到另一个Activity到选项卡片段

时间:2017-11-04 17:47:06

标签: java android android-fragments

我在MainActivity中有一个变量,我已成功传递给StoriesActivity。

问题在于从那里到StoriesFragment,这是TabLayout标签。

我了解Intents和Bundles但我不确定它们在这种情况下是如何工作的。

这是StoriesActivity:

public class StoriesActivity extends AppCompatActivity {

    //This is our tablayout
    private TabLayout tabLayout;

    //This is our viewPager
    private ViewPager viewPager;

    private Toolbar toolbar;

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

        /* +++ START Intent +++ */
        Bundle extras = getIntent().getExtras();

        final int authorID = extras.getInt("author_id");
        final String authorName = extras.getString("author_name");
        Log.i("click", Integer.toString(authorID));
        // this is successful
        /* +++ END Intent +++ */

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setTitle(authorName);
        setSupportActionBar(toolbar);

        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        viewPager = (ViewPager) findViewById(R.id.viewpager);
        setupViewPager(viewPager);

        tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);
    }

    private void setupViewPager(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        adapter.addFragment(new StoriesFragment(), "Stories");
        adapter.addFragment(new CollectionsFragment(), "Collections");
        viewPager.setAdapter(adapter);
    }

    class ViewPagerAdapter extends FragmentPagerAdapter {
        private final List<Fragment> mFragmentList = new ArrayList<>();
        private final List<String> mFragmentTitleList = new ArrayList<>();

        public ViewPagerAdapter(FragmentManager manager) {
            super(manager);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragmentList.get(position);
        }

        @Override
        public int getCount() {
            return mFragmentList.size();
        }

        public void addFragment(Fragment fragment, String title) {
            mFragmentList.add(fragment);
            mFragmentTitleList.add(title);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitleList.get(position);
        }
    }
}

这就是StoriesFragment(目前无效,因为它没有从StoriesActivity访问authorID变量):

public class StoriesFragment extends Fragment {

    public StoriesFragment() {
        // Required empty public constructor
    }

    private ListView storiesListView;

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

        // link ListView object with XML ListView
        storiesListView = (ListView) findViewById(R.id.stories_list_view);

        // create new instance of DatabaseHelper
        DatabaseHelper db = new DatabaseHelper(this);

        // create list of stories through getAllStories method
        List<Book> storyList = db.getAllStories(authorID);

        // create new ArrayAdapter
        ArrayAdapter<Book> arrayAdapter =
                new ArrayAdapter<Book>(this, android.R.layout.simple_list_item_1, storyList);

        // link ListView and ArrayAdapter
        storiesListView.setAdapter(arrayAdapter);

        Log.i("test", storyList.toString());

        storiesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                Book story = (Book) storiesListView.getItemAtPosition(i);
                //Log.i("click", story);

                Intent intent = new Intent(StoriesActivity.this, StoryBodyActivity.class);
                intent.putExtra("story", story.getTitle());
                startActivity(intent);

                //Log.i("click", "That's a click!");
            }
        });

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_stories, container, false);
    }

}

StoriesTabsAdapter:

public class StoriesTabsAdapter extends FragmentPagerAdapter {

    int mNumOfTabs;


    public StoriesTabsAdapter(FragmentManager fm, int NumOfTabs) {
        super(fm);
        this.mNumOfTabs = NumOfTabs;
    }

    private String[] tabTitles = new String[]{"Stories", "Collections"};

    // overriding getPageTitle()
    @Override
    public CharSequence getPageTitle(int position) {
        return tabTitles[position];
    }

    @Override
    public Fragment getItem(int position) {

        switch (position) {
            case 0:
                StoriesFragment tab1 = new StoriesFragment();
                return tab1;
            case 1:
                CollectionsFragment tab2 = new CollectionsFragment();
                return tab2;
            default:
                return null;
        }

    }

    @Override
    public int getCount() {
        return tabTitles.length;
    }

}

2 个答案:

答案 0 :(得分:1)

以下是您问题的解决方案:

这是你的活动:

public class StoriesActivity extends AppCompatActivity {

    //This is our tablayout
    private TabLayout tabLayout;

    //This is our viewPager
    private ViewPager viewPager;

    private Toolbar toolbar;

    private int authorID;
    private String authorName;

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

        /* +++ START Intent +++ */
        Bundle extras = getIntent().getExtras();

        authorID = extras.getInt("author_id");
        authorName = extras.getString("author_name");
        Log.i("click", Integer.toString(authorID));
        // this is successful
        /* +++ END Intent +++ */

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setTitle(authorName);
        setSupportActionBar(toolbar);

        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        viewPager = (ViewPager) findViewById(R.id.viewpager);
        setupViewPager(viewPager);

        tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);
    }

    private void setupViewPager(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        adapter.addFragment(StoriesFragment.newInstance(authorID, authorName), "Stories");
        adapter.addFragment(new CollectionsFragment(), "Collections");
        viewPager.setAdapter(adapter);
    }

    class ViewPagerAdapter extends FragmentPagerAdapter {
        private final List<Fragment> mFragmentList = new ArrayList<>();
        private final List<String> mFragmentTitleList = new ArrayList<>();

        public ViewPagerAdapter(FragmentManager manager) {
            super(manager);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragmentList.get(position);
        }

        @Override
        public int getCount() {
            return mFragmentList.size();
        }

        public void addFragment(Fragment fragment, String title) {
            mFragmentList.add(fragment);
            mFragmentTitleList.add(title);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitleList.get(position);
        }
    }
}

这是你的片段:

public class StoriesFragment extends Fragment {

    private int authorID;
    private String authorName;

    public StoriesFragment() {
        // Required empty public constructor
    }

    public static StoriesFragment newInstance(int authorID, String authorName) {

        Bundle args = new Bundle();
        args.putInt("author_id", authorID);
        args.putString("author_name", authorName);

        StoriesFragment fragment = new StoriesFragment();
        fragment.setArguments(args);
        return fragment;
    }

    private ListView storiesListView;

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

        // Here is your arguments
        authorID = getArguments().getInt("author_id");
        authorName = getArguments().getString("author_name");

        // link ListView object with XML ListView
        storiesListView = (ListView) findViewById(R.id.stories_list_view);

        // create new instance of DatabaseHelper
        DatabaseHelper db = new DatabaseHelper(this);

        // create list of stories through getAllStories method
        List<Book> storyList = db.getAllStories(authorID);

        // create new ArrayAdapter
        ArrayAdapter<Book> arrayAdapter =
                new ArrayAdapter<Book>(this, android.R.layout.simple_list_item_1, storyList);

        // link ListView and ArrayAdapter
        storiesListView.setAdapter(arrayAdapter);

        Log.i("test", storyList.toString());

        storiesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                Book story = (Book) storiesListView.getItemAtPosition(i);
                //Log.i("click", story);

                Intent intent = new Intent(StoriesActivity.this, StoryBodyActivity.class);
                intent.putExtra("story", story.getTitle());
                startActivity(intent);

                //Log.i("click", "That's a click!");
            }
        });

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_stories, container, false);
    }

}

希望它会对你有所帮助。

答案 1 :(得分:0)

从StoriesActivity发送捆绑数据

 private void setupViewPager(ViewPager viewPager) {
     Bundle bundle = new Bundle();
     bundle.putString("your_key", "yourdata");
    // set Fragmentclass Arguments
    StoriesFragment fragStory = new StoriesFragment();
    fragStory.setArguments(bundle);
    ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
    adapter.addFragment(fragStory, "Stories");
    adapter.addFragment(new CollectionsFragment(), "Collections");
    viewPager.setAdapter(adapter);
}