7

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

我希望能够使用带有标签的滑动视图以两种不同的布局(列表和地图)显示我的可搜索活动的结果。我必须将 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;
}
}
4

5 回答 5

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;

}

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

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

于 2013-10-15T17:06:58.737 回答
6

通常活动将引用其片段。在您SearchableActivity.java的情况下,您还加载PlaceListFragment.java或者setContentView(activity_searchable.xml);您需要创建片段的实例并使用FragmentTransaction.

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

培训链接

于 2013-09-22T23:31:56.940 回答
5
Bundle bundle = new Bundle();
bundle.putString("edttext", "From Activity");
// set Fragmentclass Arguments
Fragmentclass fragobj = new Fragmentclass();
fragobj.setArguments(bundle);

并在片段 onCreateView 方法中:

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

在这里查看详细答案..

于 2014-06-17T14:14:23.633 回答
1

“将数据从 Activity 发送到 Fragment”

活动:

        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");
        ...
        ...
        ...
        }
于 2014-01-13T23:21:23.237 回答
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()
.........

创建 Session 模型类是这样的。

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;
    }

}
于 2016-02-12T12:30:34.030 回答