2015-10-07 70 views
0

我試圖將我的主要活動期間檢索和創建的對象創建方法傳遞給我的滑動選項卡布局的片段之一。將對象傳遞到滑動選項卡片段創建

由於此對象是通過網絡連接創建的,因此我的計劃是在創建主活動期間接收數據,然後將生成的對象傳遞給我的片段。然而,說起來似乎容易做起來難。然後,生成的對象將傳遞到Forecast片段中的回收站視圖。

我已經閱讀了各種方法,包括在我的模型對象上實現parcelable接口,將其存儲爲一個包並嘗試將其發送到片段。但它總是出現空白。我相信這是由於我在內存中創建了一個新的片段,而不是將該包傳遞給顯示的片段。我也沒有任何碎片的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

當你做下面這段代碼,就可以到手的數據到您的片段。

您的活動,請撥打下方,當數據準備就緒:

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 
     } 
    } 
+0

當我設置適配器和viewpager後,我在我的MainActivity.java onCreate方法中調用這個時,我得到一個空指針異常。似乎是片段還沒有創建。有什麼想法做什麼?這裏是我用來設置數據的代碼'ForecastFragment fragment =(ForecastFragment)mAdapter.getRegisteredFragment(mViewPager.getCurrentItem());如果(片段!=空){ fragment.setData(mForecasts); }' – user4956079

+0

我認爲使用Interface來獲取當前片段會更好。當你的片段開始時,你的片段可以調用一個活動的方法。你必須確保你的Fragment已經加載並嘗試訪問它。 – Jun

+0

簡而言之,在片段中啓動OnCreate時調用活動的功能。 – Jun

相關問題