如何将数据从Activity发送到Fragment

时间:2013-09-22 23:19:06

标签: android android-layout android-fragments android-view android-tabs

我知道这里有很多关于此的话题。我也多次阅读文档,但我找不到将数据从活动传递到片段的最佳方法。

我希望能够使用swipe Views with tabs在两个不同的布局(列表和地图)中显示我的可搜索活动的结果。我必须将2个数据传递给片段:“currentLocation”是当前用户位置,“result”是对象列表。

我已经省略了代码的某些部分,以使其更容易理解。

SearchableActivity.java

public class SearchableActivity extends ActionBarActivity implements TabListener {

    List<PlaceModel> result = new ArrayList<PlaceModel>();
    private SearchView mSearchView;
    private String currentLocation;

    AppSectionsPagerAdapter mAppSectionsPagerAdapter;
        ViewPager mViewPager;

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

    setContentView(R.layout.activity_searchable);

    final ActionBar actionBar = getSupportActionBar();
    actionBar.setHomeButtonEnabled(true);
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

    mAppSectionsPagerAdapter = new AppSectionsPagerAdapter(getSupportFragmentManager());

    mViewPager = (ViewPager) findViewById(R.id.pager);
    mViewPager.setAdapter(mAppSectionsPagerAdapter);
    mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
        @Override
        public void onPageSelected(int position) {
            actionBar.setSelectedNavigationItem(position);
        }
    });

    actionBar.addTab(actionBar.newTab().setText("List").setTabListener(this));
    actionBar.addTab(actionBar.newTab().setText("Map").setTabListener(this));

    // get currentLocation here

    handleIntent(getIntent());
}

@Override
protected void onNewIntent(Intent intent) {
    handleIntent(intent);
}

private void handleIntent(Intent intent) {

    if (Intent.ACTION_SEARCH.equals(intent.getAction())) {

        final String query = intent.getStringExtra(SearchManager.QUERY);

        // get result here
    }
}

@Override
public void onTabReselected(Tab arg0, FragmentTransaction arg1) {
    // TODO Auto-generated method stub

}

@Override
public void onTabSelected(Tab tab, FragmentTransaction arg1) {
    mViewPager.setCurrentItem(tab.getPosition());
}

@Override
public void onTabUnselected(Tab arg0, FragmentTransaction arg1) {
    // TODO Auto-generated method stub

}

}

PlaceListFragment.java

public class PlaceListFragment extends Fragment {
    ListView listViewData;
    PlaceAdapter placeAdapter;
    List<PlaceModel> result = new ArrayList<PlaceModel>();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_list, container, false);
        Bundle args = getArguments();
        listViewData = (ListView) rootView.findViewById(android.R.id.list);
        // I will pass result and currentLocation here
        placeAdapter = new PlaceAdapter(getActivity(), R.layout.fragment_list_item, result, currentLocation);
        listViewData.setAdapter(placeAdapter);
        return rootView;
    }
}

AppSectionsPagerAdapter.java

public class AppSectionsPagerAdapter extends FragmentPagerAdapter {

final int PAGE_COUNT = 2;

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

@Override
public Fragment getItem(int arg0) {
    Bundle data = new Bundle();
    switch(arg0) {
        case 0:
            PlaceListFragment fragment1 = new PlaceListFragment();
            fragment1.setArguments(data);
            return fragment1;
        default:
            PlaceListFragment fragment2 = new PlaceListFragment();
            fragment2.setArguments(data);
            return fragment2;
    }
}

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

6 个答案:

答案 0 :(得分:29)

从活动中您按意图发送数据:

Bundle bundle=new Bundle();
bundle.putString("name", "From Activity");
  //set Fragmentclass Arguments
Fragmentclass fragobj=new Fragmentclass();
fragobj.setArguments(bundle);

并在Fragment onCreateView方法中:

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {
          String strtext=getArguments().getString("name");

    return inflater.inflate(R.layout.fragment, container, false);
    }

答案 1 :(得分:7)

在Activity onCreate中查找片段,并将数据设置为您在片段中编写的方法:

        ExampleFragment rf =  (ExampleFragment) getSupportFragmentManager().findFragmentById(R.id.exampleFragment);

    if(rf!=null){
    rf.setExample(currentExample);
    }

“CurrentExample”是您要发送到片段中“setExample”方法的任何内容。

public void setExample(ExampleObject currentExample){

    currentExampleInFragment = currentExample;

}

您可以使用片段的onActivityCreated方法中的数据。

不确定这是否是一个好的解决方案,但我发现它是传递对象最简单的方法。

答案 2 :(得分:6)

通常活动会引用他们的片段。在您的SearchableActivity.java中,您还要在PlaceListFragment.java中加载setContentView(activity_searchable.xml);,或者您需要创建片段的实例并使用FragmentTransaction添加/替换片段。

你可以在这里找到一个很好的例子,说明如何在片段之间或在活动之间进行通信。片段。

Training link

答案 3 :(得分:4)

Bundle bundle = new Bundle();
bundle.putString("edttext", "From Activity");
// set Fragmentclass Arguments
Fragmentclass fragobj = new Fragmentclass();
fragobj.setArguments(bundle);

并在Fragment onCreateView方法中:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    String strtext = getArguments().getString("edttext");    
    return inflater.inflate(R.layout.fragment, container, false);
}

在此处查看详细信息answer ..

答案 4 :(得分:1)

“将数据从活动发送到片段”

<强>活动:

        Bundle bundle = new Bundle();
        bundle.putString("message", "Alo Stackoverflow!");
        FragmentClass fragInfo = new FragmentClass();
        fragInfo.setArguments(bundle);
        transaction.replace(R.id.fragment_single, fragInfo);
        transaction.commit();

<强>片段:

读取片段中的值

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        Bundle bundle = this.getArguments();
        String myValue = bundle.getString("message");
        ...
        ...
        ...
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        String myValue = this.getArguments().getString("message");
        ...
        ...
        ...
        }

答案 5 :(得分:1)

创建一个Session模型类,并在Activity中设置需要发送数据的值,然后在Fragment中,您可以从Session模型类中获取该值

例如。根据你的活动你可以这样设置。

 AllEventDetails.getInstance().setEvent_description(event_Description);
AllEventDetails.getInstance().setDj_name(dj_name);
AllEventDetails.getInstance().setMusic_theme(music_theme);
AllEventDetails.getInstance().setClub_name(club_name);
AllEventDetails.getInstance().setDate(event_date);
AllEventDetails.getInstance().setBanner_image_path(banner_image_path);
AllEventDetails.getInstance().setEvent_title(event_title);  

从你的片段中你可以像这样回复。

AllEventDetails.getInstance().getClub_name()
.........

创建会话模型类就是这样。

public class AllEventDetails {
    private static AllEventDetails mySession ;
    private String event_description;
    private String dj_name;
    private String music_theme;
    private String club_name;
    private String date;
    private String banner_image_path;
    private String event_title;

    private AllEventDetails() {     
        event_description = null;
        dj_name = null;
        music_theme = null;
        club_name = null;
        date = null;
        banner_image_path = null;
        event_title = null;

    }

    public static AllEventDetails getInstance() {
        if( mySession == null ) {
            mySession = new AllEventDetails() ;
        }
        return mySession ;
    }

    public void resetSession() {
        mySession=null;
    }
    public String getEvent_description() {
        return event_description;
    }
    public void setEvent_description(String event_description) {
        this.event_description = event_description;
    }
    public String getDj_name() {
        return dj_name;
    }
    public void setDj_name(String dj_name) {
        this.dj_name = dj_name;
    }
    public String getMusic_theme() {
        return music_theme;
    }
    public void setMusic_theme(String music_theme) {
        this.music_theme = music_theme;
    }
    public String getClub_name() {
        return club_name;
    }
    public void setClub_name(String club_name) {
        this.club_name = club_name;
    }
    public String getDate() {
        return date;
    }
    public void setDate(String date) {
        this.date = date;
    }
    public String getBanner_image_path() {
        return banner_image_path;
    }
    public void setBanner_image_path(String banner_image_path) {
        this.banner_image_path = banner_image_path;
    }
    public String getEvent_title() {
        return event_title;
    }
    public void setEvent_title(String event_title) {
        this.event_title = event_title;
    }

}