如何在 FragmentPagerAdapter 中的片段之间传递数据

对于我的学术项目,我想创建一个带有 4 个选项卡的应用程序。第一个将显示最近添加到列表中的游戏,第二个将是搜索表单,第三个将显示搜索结果,最后一个将显示详细信息。TabView我目前已经为4 个选项卡创建了代码。问题是我想执行搜索以获取列表中符合片段 2 搜索条件的项目,但我不知道如何将片段 2 中的数据(textView 数据和微调器)传递给片段3.我的代码如下:


MainActivity.java:


import android.os.Bundle;

import android.support.design.widget.FloatingActionButton;

import android.support.design.widget.Snackbar;

import android.support.design.widget.TabLayout;

import android.view.MenuInflater;

import android.view.View;

import android.support.design.widget.NavigationView;

import android.support.v4.view.GravityCompat;

import android.support.v4.widget.DrawerLayout;

import android.support.v7.app.ActionBarDrawerToggle;

import android.support.v7.app.AppCompatActivity;

import android.support.v7.widget.Toolbar;

import android.view.Menu;

import android.view.MenuItem;

import android.support.v4.view.PagerAdapter;

import android.support.v4.view.ViewPager;

import android.widget.Button;

import android.widget.Toast;



public class MainActivity extends AppCompatActivity

    implements NavigationView.OnNavigationItemSelectedListener {




    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);



        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);

        setSupportActionBar(toolbar);


        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);

        fab.setImageResource(R.drawable.ic_search_white_24dp);

        fab.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View view) {

                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)

                    .setAction("Action", null).show();

            }

        });


临摹微笑
浏览 129回答 3
3回答

鸿蒙传说

尝试这个使用 bundle 在两个片段之间传递值import android.support.v4.app.Fragment;import android.support.v4.app.FragmentManager;import android.support.v4.app.FragmentPagerAdapter;public class TabPagerAdapter extends FragmentPagerAdapter{int tabCount; public TabPagerAdapter(FragmentManager fm, int numberOfTabs) {super(fm);this.tabCount = numberOfTabs;} @Overridepublic Fragment getItem(int position) {switch (position) {    case 0:        return  new HomeScreenFragment();    case 1:        return new SearchFormFragment();    case 2:       Fragment fragment = new SearchResultsFragment()     Bundle args = new Bundle();     args.putString("Key", "Value");     fragment.setArguments(args);        return fragment;    case 3:        return new DetailsScreenFragment();    default:        return null;   }}    @Override     public int getCount() {   return tabCount;   }   }在 SearchResultsFragment 的 onCreateView(....) 中 String value = getArguments().getString("Key"); public class SearchResultsFragment extends Fragment {TextView infoTextView;ListView listViewGames;  public SearchResultsFragment() {   // Required empty public constructor }  @Override  public View onCreateView(LayoutInflater inflater, ViewGroup container,                     Bundle savedInstanceState) {   View searchResultsView =   inflater.inflate(R.layout.fragment_search_results, container, false);    String value = getArguments().getString("Key");   return searchResultsView; } private void findViews(){ infoTextView = getActivity().findViewById(R.id.info_textView);listViewGames = getActivity().findViewById(R.id.games_listView); } }跳它帮助你

千万里不及你

您可以通过多种方式在片段之间传递对象/值。在您的情况下,最简单的解决方案是将这些值委托给控股公司Activityie MainActivity。主要活动:import android.os.Bundle;import android.support.design.widget.FloatingActionButton;import android.support.design.widget.Snackbar;import android.support.design.widget.TabLayout;import android.view.MenuInflater;import android.view.View;import android.support.design.widget.NavigationView;import android.support.v4.view.GravityCompat;import android.support.v4.widget.DrawerLayout;import android.support.v7.app.ActionBarDrawerToggle;import android.support.v7.app.AppCompatActivity;import android.support.v7.widget.Toolbar;import android.view.Menu;import android.view.MenuItem;import android.support.v4.view.PagerAdapter;import android.support.v4.view.ViewPager;import android.widget.Button;import android.widget.Toast;public class MainActivity extends AppCompatActivity&nbsp; &nbsp; implements NavigationView.OnNavigationItemSelectedListener {//these will hold your valuesString filterGameTitle;int filterGenreId;@Overrideprotected void onCreate(Bundle savedInstanceState) {&nbsp; &nbsp; super.onCreate(savedInstanceState);&nbsp; &nbsp; setContentView(R.layout.activity_main);&nbsp; &nbsp; Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);&nbsp; &nbsp; setSupportActionBar(toolbar);&nbsp; &nbsp; FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);&nbsp; &nbsp; fab.setImageResource(R.drawable.ic_search_white_24dp);&nbsp; &nbsp; fab.setOnClickListener(new View.OnClickListener() {&nbsp; &nbsp; &nbsp; &nbsp; @Override&nbsp; &nbsp; &nbsp; &nbsp; public void onClick(View view) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .setAction("Action", null).show();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; });&nbsp; &nbsp; //TabLayout function call&nbsp; &nbsp; configureTabLayout();&nbsp; &nbsp; DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);&nbsp; &nbsp; ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);&nbsp; &nbsp; drawer.addDrawerListener(toggle);&nbsp; &nbsp; toggle.syncState();&nbsp; &nbsp; NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);&nbsp; &nbsp; navigationView.setNavigationItemSelectedListener(this);}@Overridepublic void onBackPressed() {&nbsp; &nbsp; DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);&nbsp; &nbsp; if (drawer.isDrawerOpen(GravityCompat.START)) {&nbsp; &nbsp; &nbsp; &nbsp; drawer.closeDrawer(GravityCompat.START);&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; super.onBackPressed();&nbsp; &nbsp; }}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {&nbsp; &nbsp; // Inflate the menu; this adds items to the action bar if it is present.&nbsp; &nbsp; MenuInflater inflater = getMenuInflater();&nbsp; &nbsp; inflater.inflate(R.menu.main, menu);&nbsp; &nbsp; return true;}@Overridepublic boolean onOptionsItemSelected(MenuItem item) {&nbsp; &nbsp; switch (item.getItemId()){&nbsp; &nbsp; &nbsp; &nbsp; case R.id.menu_exit:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; finish();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return true;&nbsp; &nbsp; &nbsp; &nbsp; case R.id.menu_settings:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Toast.makeText(this, "Under Construction", Toast.LENGTH_LONG).show();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return true;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; default:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return super.onOptionsItemSelected(item);&nbsp; &nbsp; }}@SuppressWarnings("StatementWithEmptyBody")@Overridepublic boolean onNavigationItemSelected(MenuItem item) {&nbsp; &nbsp; // Handle navigation view item clicks here.&nbsp; &nbsp; int id = item.getItemId();&nbsp; &nbsp; if (id == R.id.nav_camera) {&nbsp; &nbsp; &nbsp; &nbsp; // Handle the camera action&nbsp; &nbsp; } else if (id == R.id.nav_gallery) {&nbsp; &nbsp; } else if (id == R.id.nav_slideshow) {&nbsp; &nbsp; } else if (id == R.id.nav_manage) {&nbsp; &nbsp; } else if (id == R.id.nav_share) {&nbsp; &nbsp; } else if (id == R.id.nav_send) {&nbsp; &nbsp; }&nbsp; &nbsp; DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);&nbsp; &nbsp; drawer.closeDrawer(GravityCompat.START);&nbsp; &nbsp; return true;}//Tab Layout function declarationprivate void configureTabLayout() {&nbsp; &nbsp; //Getting the tab layout&nbsp; &nbsp; TabLayout tabLayout = findViewById(R.id.tab_layout);&nbsp; &nbsp; //Adding Tabs&nbsp; &nbsp; tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.ic_home_white_24dp));&nbsp; &nbsp; tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.ic_search_white_24dp));&nbsp; &nbsp; tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.ic_results_white_24dp));&nbsp; &nbsp; tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.ic_details_white_24dp));&nbsp; &nbsp; //The TabPagerAdapter instance is then&nbsp; &nbsp; //assigned as the adapter for the ViewPager and the TabLayout component added&nbsp; &nbsp; //to the page change listener&nbsp; &nbsp; final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);&nbsp; &nbsp; final PagerAdapter adapter = new TabPagerAdapter&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; (getSupportFragmentManager(), tabLayout.getTabCount());&nbsp; &nbsp; viewPager.setAdapter(adapter);&nbsp; &nbsp; //Finally, the onTabSelectedListener is configured on the TabLayout instance and&nbsp; &nbsp; //the onTabSelected() method implemented to set the current page on the&nbsp; &nbsp; //ViewPager based on the currently selected tab number.&nbsp; &nbsp; viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));&nbsp; &nbsp; tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {&nbsp; &nbsp; &nbsp; &nbsp; @Override&nbsp; &nbsp; &nbsp; &nbsp; public void onTabSelected(TabLayout.Tab tab) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; viewPager.setCurrentItem(tab.getPosition());&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; @Override&nbsp; &nbsp; &nbsp; &nbsp; public void onTabUnselected(TabLayout.Tab tab) {&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; @Override&nbsp; &nbsp; &nbsp; &nbsp; public void onTabReselected(TabLayout.Tab tab) {&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; });}}搜索表单片段:import android.content.Intent;import android.os.Bundle;import android.support.v4.app.Fragment;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ArrayAdapter;import android.widget.Button;import android.widget.EditText;import android.widget.Spinner;import android.widget.TextView;import android.widget.Toast;/**&nbsp;* A simple {@link Fragment} subclass.&nbsp;*/public class SearchFormFragment extends Fragment {private Button searchButton;private EditText gameTitleEditText;Spinner spinnerGenre;public SearchFormFragment() {&nbsp; &nbsp; // Required empty public constructor}@Overridepublic View onCreateView(final LayoutInflater inflater, ViewGroup container,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Bundle savedInstanceState) {&nbsp; &nbsp; View searchFormView = inflater.inflate(R.layout.fragment_search_form, container, false);&nbsp; &nbsp; searchButton = searchFormView.findViewById(R.id.searchButton);&nbsp; &nbsp; gameTitleEditText = searchFormView.findViewById(R.id.game_title_editText);&nbsp; &nbsp; spinnerGenre = searchFormView.findViewById(R.id.genre_spinner);&nbsp; &nbsp; ArrayAdapter<CharSequence> genreAdapter = ArrayAdapter.createFromResource(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; getActivity(),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; R.array.game_genres,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; android.R.layout.simple_spinner_item&nbsp; &nbsp; );&nbsp; &nbsp; genreAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);&nbsp; &nbsp; spinnerGenre.setAdapter(genreAdapter);&nbsp; &nbsp; searchButton.setOnClickListener(new View.OnClickListener() {&nbsp; &nbsp; &nbsp; &nbsp; @Override&nbsp; &nbsp; &nbsp; &nbsp; public void onClick(View v) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; String filterGameTitle = gameTitleEditText.getText().toString();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; int filterGenreId = spinnerGenre.getSelectedItemPosition();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ((MainActivity)getActivity()).filterGameTitle = filterGameTitle;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ((MainActivity)getActivity()).filterGenreId = filterGenreId;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; String message = String.format("Game Title: %s\n Genre: %s", filterGameTitle, filterGenreId);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Toast.makeText(getActivity(),message, Toast.LENGTH_LONG).show();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; });&nbsp; &nbsp; // Inflate the layout for this fragment&nbsp; &nbsp; //return inflater.inflate(R.layout.fragment_search_form, container, false);&nbsp; &nbsp; return searchFormView;}}搜索结果片段:import android.content.Intent;import android.os.Bundle;import android.support.v4.app.Fragment;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ListView;import android.widget.TextView;/**&nbsp;* A simple {@link Fragment} subclass.&nbsp;*/public class SearchResultsFragment extends Fragment {TextView infoTextView;ListView listViewGames;String filterGameTitle;int filterGenreId;public SearchResultsFragment() {&nbsp; &nbsp; // Required empty public constructor}@Overridepublic void onAttach(Context context){&nbsp; &nbsp; filterGameTitle = ((MainActivity)getActivity()).filterGameTitle;&nbsp; &nbsp; filterGenreId = ((MainActivity)getActivity()).filterGenreId;&nbsp; &nbsp; super.onAttach(context);}@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Bundle savedInstanceState) {&nbsp; &nbsp; View searchResultsView = inflater.inflate(R.layout.fragment_search_results, container, false);&nbsp; &nbsp; return searchResultsView;}private void findViews(){&nbsp; &nbsp; infoTextView = getActivity().findViewById(R.id.info_textView);&nbsp; &nbsp; listViewGames = getActivity().findViewById(R.id.games_listView);}}

梦里花落0921

您可以使用接口将您的搜索字符串从片段 2 发送到您的活动,并且您可以从它们调用片段 3 中的所有方法,因为片段3 对象将在您的活动中对您可用,您可以在片段 3 中创建 performSearch() 和从您的活动中调用它。或者,您可以使用事件总线之类的东西来避免设置界面所需的样板代码。看看这个事件总线 repo https://github.com/greenrobot/EventBus 在你想要搜索字符串的地方注册事件总线,在你的情况下,像这样在 Fragment3 中注册事件总线&nbsp; @Override&nbsp;public void onStart() {&nbsp;super.onStart();&nbsp;EventBus.getDefault().register(this);&nbsp;}&nbsp;@Override&nbsp;public void onStop() {&nbsp;super.onStop();&nbsp;EventBus.getDefault().unregister(this);&nbsp;}在您的 Fragment 3 中创建一个这样的函数&nbsp; &nbsp; @Subscribepublic void onSearchEvent(String searchString){&nbsp;//you will get your search string here}现在从您要发送 searchString 的位置返回到 fragment2,您必须将下面的代码从您要发送 searchString 的位置放入,并且这个发布的 searchString 将由 Fragment 3 在其 onSearchEvent 方法中接收EventBus.getDefault().post(searchString);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java