为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

临摹微笑 2022-06-15 15:16:03
对于我的学术项目,我想创建一个带有 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();            }        });
查看完整描述

3 回答

?
鸿蒙传说

TA贡献1865条经验 获得超7个赞

尝试这个


使用 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;

}


 @Override

public 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);

 }

 }

跳它帮助你


查看完整回答
反对 回复 2022-06-15
?
千万里不及你

TA贡献1784条经验 获得超9个赞

您可以通过多种方式在片段之间传递对象/值。在您的情况下,最简单的解决方案是将这些值委托给控股公司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

    implements NavigationView.OnNavigationItemSelectedListener {

//these will hold your values

String filterGameTitle;

int filterGenreId;


@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();

        }

    });


    //TabLayout function call

    configureTabLayout();


    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);

    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(

            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);

    drawer.addDrawerListener(toggle);

    toggle.syncState();


    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);

    navigationView.setNavigationItemSelectedListener(this);

}


@Override

public void onBackPressed() {

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);

    if (drawer.isDrawerOpen(GravityCompat.START)) {

        drawer.closeDrawer(GravityCompat.START);

    } else {

        super.onBackPressed();

    }

}


@Override

public boolean onCreateOptionsMenu(Menu menu) {

    // Inflate the menu; this adds items to the action bar if it is present.

    MenuInflater inflater = getMenuInflater();

    inflater.inflate(R.menu.main, menu);

    return true;

}


@Override

public boolean onOptionsItemSelected(MenuItem item) {


    switch (item.getItemId()){

        case R.id.menu_exit:

            finish();

            return true;

        case R.id.menu_settings:

            Toast.makeText(this, "Under Construction", Toast.LENGTH_LONG).show();

            return true;

            default:

                return super.onOptionsItemSelected(item);

    }

}


@SuppressWarnings("StatementWithEmptyBody")

@Override

public boolean onNavigationItemSelected(MenuItem item) {

    // Handle navigation view item clicks here.

    int id = item.getItemId();


    if (id == R.id.nav_camera) {

        // Handle the camera action

    } else if (id == R.id.nav_gallery) {


    } else if (id == R.id.nav_slideshow) {


    } else if (id == R.id.nav_manage) {


    } else if (id == R.id.nav_share) {


    } else if (id == R.id.nav_send) {


    }


    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);

    drawer.closeDrawer(GravityCompat.START);

    return true;

}





//Tab Layout function declaration

private void configureTabLayout() {


    //Getting the tab layout

    TabLayout tabLayout = findViewById(R.id.tab_layout);


    //Adding Tabs

    tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.ic_home_white_24dp));

    tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.ic_search_white_24dp));

    tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.ic_results_white_24dp));

    tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.ic_details_white_24dp));



    //The TabPagerAdapter instance is then

    //assigned as the adapter for the ViewPager and the TabLayout component added

    //to the page change listener

    final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);

    final PagerAdapter adapter = new TabPagerAdapter

            (getSupportFragmentManager(), tabLayout.getTabCount());

    viewPager.setAdapter(adapter);



    //Finally, the onTabSelectedListener is configured on the TabLayout instance and

    //the onTabSelected() method implemented to set the current page on the

    //ViewPager based on the currently selected tab number.

    viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));

    tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {

        @Override

        public void onTabSelected(TabLayout.Tab tab) {

            viewPager.setCurrentItem(tab.getPosition());

        }

        @Override

        public void onTabUnselected(TabLayout.Tab tab) {

        }

        @Override

        public void onTabReselected(TabLayout.Tab tab) {

        }

    });

}

}

搜索表单片段:


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;



/**

 * A simple {@link Fragment} subclass.

 */

public class SearchFormFragment extends Fragment {


private Button searchButton;

private EditText gameTitleEditText;


Spinner spinnerGenre;




public SearchFormFragment() {

    // Required empty public constructor

}


@Override

public View onCreateView(final LayoutInflater inflater, ViewGroup container,

                         Bundle savedInstanceState) {


    View searchFormView = inflater.inflate(R.layout.fragment_search_form, container, false);


    searchButton = searchFormView.findViewById(R.id.searchButton);

    gameTitleEditText = searchFormView.findViewById(R.id.game_title_editText);

    spinnerGenre = searchFormView.findViewById(R.id.genre_spinner);


    ArrayAdapter<CharSequence> genreAdapter = ArrayAdapter.createFromResource(

            getActivity(),

            R.array.game_genres,

            android.R.layout.simple_spinner_item

    );


    genreAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    spinnerGenre.setAdapter(genreAdapter);



    searchButton.setOnClickListener(new View.OnClickListener() {

        @Override

        public void onClick(View v) {

            String filterGameTitle = gameTitleEditText.getText().toString();

            int filterGenreId = spinnerGenre.getSelectedItemPosition();

            ((MainActivity)getActivity()).filterGameTitle = filterGameTitle;

            ((MainActivity)getActivity()).filterGenreId = filterGenreId;

            String message = String.format("Game Title: %s\n Genre: %s", filterGameTitle, filterGenreId);

            Toast.makeText(getActivity(),message, Toast.LENGTH_LONG).show();


        }

    });


    // Inflate the layout for this fragment

    //return inflater.inflate(R.layout.fragment_search_form, container, false);

    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;



/**

 * A simple {@link Fragment} subclass.

 */

public class SearchResultsFragment extends Fragment {


TextView infoTextView;

ListView listViewGames;


String filterGameTitle;

int filterGenreId;


public SearchResultsFragment() {

    // Required empty public constructor

}


@Override

public void onAttach(Context context)

{

    filterGameTitle = ((MainActivity)getActivity()).filterGameTitle;

    filterGenreId = ((MainActivity)getActivity()).filterGenreId;


    super.onAttach(context);

}



@Override

public View onCreateView(LayoutInflater inflater, ViewGroup container,

                         Bundle savedInstanceState) {


    View searchResultsView = inflater.inflate(R.layout.fragment_search_results, container, false);


    return searchResultsView;

}


private void findViews()

{

    infoTextView = getActivity().findViewById(R.id.info_textView);

    listViewGames = getActivity().findViewById(R.id.games_listView);

}



}


查看完整回答
反对 回复 2022-06-15
?
梦里花落0921

TA贡献1772条经验 获得超6个赞

您可以使用接口将您的搜索字符串从片段 2 发送到您的活动,并且您可以从它们调用片段 3 中的所有方法,因为片段3 对象将在您的活动中对您可用,您可以在片段 3 中创建 performSearch() 和从您的活动中调用它。或者,您可以使用事件总线之类的东西来避免设置界面所需的样板代码。


看看这个事件总线 repo https://github.com/greenrobot/EventBus 在你想要搜索字符串的地方注册事件总线,在你的情况下,像这样在 Fragment3 中注册事件总线


  @Override

 public void onStart() {

 super.onStart();

 EventBus.getDefault().register(this);

 }


 @Override

 public void onStop() {

 super.onStop();

 EventBus.getDefault().unregister(this);

 }

在您的 Fragment 3 中创建一个这样的函数


    @Subscribe

public void onSearchEvent(String searchString){

 //you will get your search string here

}

现在从您要发送 searchString 的位置返回到 fragment2,您必须将下面的代码从您要发送 searchString 的位置放入,并且这个发布的 searchString 将由 Fragment 3 在其 onSearchEvent 方法中接收


EventBus.getDefault().post(searchString);


查看完整回答
反对 回复 2022-06-15
  • 3 回答
  • 0 关注
  • 128 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信