我有一个应用程序,它从viewPager启动,有点像Snapchat作为参考。基于当前模式,即: 初始化片段上的所有内容已创建; UI线程被阻塞,应用程序需要相当长的时间才能启动。
我该怎么办?因为我需要在主线程本身上处理这些对象。
答案 0 :(得分:1)
在你的片段中创建一个像这样的静态实例
public static FragmentSample newInstance(Datamodel Model) {
FragmentBatch fragment = new FragmentBatch();
Bundle args = new Bundle();
args.putParcelable("extra",Model);
fragment.setArguments(args);
return fragment;
}
并在活动的部分适配器</ p>中初始化它
public class SampleActivity extends AppCompatActivity {
/**
* The {@link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {@link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {@link android.support.v4.app.FragmentStatePagerAdapter}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {@link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
Datamodel datamodel;
int batchCount;
List<Datamodel > datamodels;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_weight_record);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
datamodels= new ArrayList<>();
datamodels.add(new Datamodel ("Neoperene", "skyperene", "", "22w441",1,"+/-1%",""));
datamodels.add(new Datamodel ("Neoperene", "skyperene", "", "22w442",2,"+/-1%",""));
datamodels.add(new Datamodel ("Neoperene", "skyperene", "", "22w443",3,"+/-1%",""));
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
switch(position){
case 0:
return FragmentSample.newInstance(Datamodel.get(0));
case 1:
return FragmentBatch.newInstance(Datamodel.get(1));
default:
return FragmentBatch.newInstance(Datamodel.get(0));
}
@Override
public int getCount() {
// Show 3 total pages.
return 3;
}
@Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "SECTION 1";
case 1:
return "SECTION 2";
case 2:
return "SECTION 3";
}
return null;
}
}
}