在创建时将对象传递给滑动选项卡片段

时间:2015-10-07 00:37:23

标签: java android android-fragments slidingmenu

我正在尝试将在创建方法的主要活动期间检索和创建的对象传递给我的滑动标签布局的一个片段。

由于此对象是通过网络连接创建的,因此我的计划是在创建Main Activity期间接收数据,然后将生成的对象传递给我的片段。然而,这似乎说起来容易做起来难。然后,生成的对象将传递到Forecast片段中的回收器视图。

我已经阅读了各种方法,包括在我的模型对象上实现parcelable接口,将其存储为bundle并尝试将其发送到片段。然而它总是无效。我相信这是因为我在内存中创建了一个新片段,而没有将bundle传递给显示的片段。我也没有任何ID片段,因此至少根据我的知识,不能通过ID找到它们。

如果有人能指出我正确的方向,我将非常感激。

主要Activity.java

public class MainActivity extends AppCompatActivity {

private static final String TAG = "MAIN ACTIVITY";
@Bind(R.id.toolBar) Toolbar mToolbar;
@Bind(R.id.viewPager) ViewPager mViewPager;
@Bind(R.id.tabLayout) SlidingTabLayout mTabLayout;

private ViewPagerAdapter mAdapter;
private String mForecastsTabName = "Forecasts";
private String mAlertsTabName = "Alerts";
private String mTabTitles[] = {mForecastsTabName, mAlertsTabName};
private  int mNumberOfTabs = 2;
private Forecast[] mForecasts;
private JsonParser mJsonParser = new JsonParser();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ButterKnife.bind(this);
    setSupportActionBar(mToolbar);

    setupSlidingTabs();
}

private void setupSlidingTabs() {
    // Creating The ViewPagerAdapter and Passing Fragment Manager, Titles fot the Tabs and Number Of Tabs.
    mAdapter = new ViewPagerAdapter(getSupportFragmentManager(), mTabTitles, mNumberOfTabs);

    // Assigning the ViewPages View and setting the adapter
    mViewPager.setAdapter(mAdapter);

    // Assigning the Sliding Tab Layout View
    mTabLayout.setDistributeEvenly(true); // To make the Tabs Fixed set this true, This makes the tabs Space Evenly in Available width
    // Setting Custom Color for the Scroll bar indicator of the Tab View
    mTabLayout.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
        @Override
        public int getIndicatorColor(int position) {
            return getResources().getColor(R.color.ColorAccent);
        }
    });

    mTabLayout.setViewPager(mViewPager);
}

预测Fragment.java

public class ForecastFragment extends Fragment {

private static final String FORECAST_KEY = "FORECAST_KEY";
private static final String TAG = "FRAGMENT";
private Forecast[] mForecasts;

@Bind(R.id.recyclerView) RecyclerView mRecyclerView;
@Bind(R.id.emptyView) TextView mEmptyView;
@Bind(R.id.locationButton) Button mLocationButton;

public static ForecastFragment newInstance(Forecast[] forecasts) {
    ForecastFragment fragment = new ForecastFragment();
    Bundle bundle = new Bundle();
    bundle.putParcelableArray(FORECAST_KEY, forecasts);
    fragment.setArguments(bundle);
    return fragment;
}

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Initialize dataset, this data would usually come from a local content provider or
    // remote server.
}

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.forecast_tab_fragment, container, false);
    ButterKnife.bind(this, view);

    displayEmptyViewIfNoData();

    ForecastAdapter adapter = new ForecastAdapter(getActivity(), mForecasts);
    mRecyclerView.setAdapter(adapter);

    RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
    mRecyclerView.setLayoutManager(layoutManager);

    return view;
}


private void displayEmptyViewIfNoData() {
    if (mForecasts == null || mForecasts.length < 1) {
        mRecyclerView.setVisibility(View.GONE);
        mEmptyView.setVisibility(View.VISIBLE);
        mLocationButton.setVisibility(View.VISIBLE);
    }
    else {
        mRecyclerView.setVisibility(View.VISIBLE);
        mEmptyView.setVisibility(View.GONE);
        mLocationButton.setVisibility(View.GONE);
    }
}

@OnClick(R.id.locationButton)
public void selectLocations(View view) {
    Intent intent = new Intent(getActivity(), LocationSelectionActivity.class);
    intent.putExtra(ActivityConstants.CALLING_ACTIVITY, ActivityConstants.FORECAST_ACTIVITY);
    startActivity(intent);
}

}

ViewPagerAdapter.java

public class ViewPagerAdapter extends FragmentStatePagerAdapter {
// This will Store the Titles of the Tabs which are Going to be passed when ViewPagerAdapter is created
String mTitles[];
// Store the number of tabs, this will also be passed when the ViewPagerAdapter is created
int mNumberOfTabs;
SparseArray<Fragment> registeredFragments = new SparseArray<>();

public ViewPagerAdapter(FragmentManager fm, String titles[], int numberOfTabs) {
    super(fm);
    mTitles = titles;
    mNumberOfTabs = numberOfTabs;
}

//This method return the fragment for the every position in the View Pager
@Override
public Fragment getItem(int position) {
    if (position == 0) {
        ForecastFragment forecastFragment = new ForecastFragment();
        return forecastFragment;
    }
    else if (position == 1) {
        AlertFragment alertFragment = new AlertFragment();
        return alertFragment;
    }
    return null;
}

@Override
public Object instantiateItem(ViewGroup container, int position) {
    Fragment fragment = (Fragment) super.instantiateItem(container, position);
    registeredFragments.put(position, fragment);
    return fragment;
}

@Override
public void destroyItem(ViewGroup container, int position, Object object) {
    registeredFragments.remove(position);
    super.destroyItem(container, position, object);
}

public Fragment getRegisteredFragment(int position) {
    return registeredFragments.get(position);
}

// This method return the titles for the Tabs in the Tab Strip
@Override
public CharSequence getPageTitle(int position) {
    return mTitles[position];
}

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

}

Forecast_tab_fragment.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@color/ColorPrimaryLight">

   <android.support.v7.widget.RecyclerView
       android:id="@+id/recyclerView"
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       android:padding="@dimen/activity_vertical_margin"/>

   <TextView
       android:id="@+id/emptyView"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:text="@string/empty_forecast_message"
       android:textColor="@color/ColorTextPrimary"
       android:gravity="center"
       android:visibility="gone"
       android:layout_alignParentTop="true"
       android:layout_alignParentLeft="true"
       android:layout_alignParentStart="true"
       android:layout_marginTop="115dp"/>

<Button
    android:id="@+id/locationButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/button_shape"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:textColor="@color/ColorTextPrimary"
    android:text="@string/add_forecast_button"
    android:visibility="gone"
    android:layout_alignParentBottom="false"
    android:layout_centerHorizontal="true"
    android:layout_below="@+id/emptyView"
    android:layout_marginTop="24dp"/>

</RelativeLayout>

1 个答案:

答案 0 :(得分:1)

当您在下面执行此代码时,您可以将数据传递给您的片段。

在您的活动中,请在数据准备就绪时调用以下内容:

mAdapter.getFragment(index).setData(dataObject);

mAdapter.getFragment(mViewPager.getCurrentItem()).setData(dataObject);

你的FragmentPagerAdater应该是这样的:

class CustomPagerAdapter extends FragmentPagerAdapter {
        SparseArray<App4StoreBaseSubFragment> registeredFragments = new SparseArray<App4StoreBaseSubFragment>();
        public CustomPagerAdapter(FragmentManager fm) {
            super(fm);
        }

@Override
    public Object instantiateItem(ViewGroup container, int position) {
        App4StoreBaseSubFragment fragment = (App4StoreBaseSubFragment) super.instantiateItem(container, position);
        registeredFragments.put(position, fragment);
        return fragment;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        registeredFragments.remove(position);
        super.destroyItem(container, position, object);
    }

        public ForecastFragment getFragment(int position){
            return registeredFragments.get(position);
        }

    }

你的片段应该是这样的:

public class ForecastFragment extends Fragment {
         public void setData(Forecast forecast){
              //write code here to change UI
         }
    }