gpt4 book ai didi

java - 在创建时将对象传递给滑动选项卡 fragment

转载 作者:行者123 更新时间:2023-12-01 11:05:38 27 4
gpt4 key购买 nike

我试图将在创建方法的主要 Activity 期间检索和创建的对象传递给滑动选项卡布局的 fragment 之一。

由于该对象是通过网络连接创建的,我的计划是在创建主 Activity 期间接收数据,然后将结果对象传递给我的 fragment 。然而,这似乎说起来容易做起来难。然后,生成的对象将传递到 Forecast fragment 中的回收器 View 。

我已经阅读了各种方法,包括在我的模型对象上实现 Parcelable 接口(interface),将其存储为 bundle 并尝试将其发送到 fragment 。然而它总是空的。我相信这是因为我在内存中创建了一个新 fragment ,并且没有将包传递给显示的 fragment 。我也没有任何 fragment 的 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>

最佳答案

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

在您的 Activity 中,当数据准备就绪时,调用以下方法:

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

}

你的 fragment 应该是这样的:

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

关于java - 在创建时将对象传递给滑动选项卡 fragment ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32981927/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com