我有一个包含4个片段的活动。每个片段都有其独立的类和布局。这是父活动类:
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
switch (position){
case 0:
return new MainFragment();
case 1:
return new CatalogFragment();
case 2:
return new FolderFragment();
case 3:
return new SettingsFragment();
default:
return null;
}
}
@Override
public int getCount() {
return 4;
}
@Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "PLAYER";
case 1:
return "CATALOG";
case 2:
return "FOLDERS";
case 3:
return "SETTINGS";
}
return null;
}
}
片段类仅用于:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main,container,false);
return view;
}
和默认构造函数。
在FragmentMain
我有2 TextView
秒。我想根据MainActivity
中的信息动态更改它们。我正在使用ViewPager
。
这是我的MainActivity
XML文件:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<ImageView
android:layout_width="match_parent"
android:layout_height="250dp"
android:id="@+id/imageView"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="false" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="@+id/textView"
android:layout_below="@+id/imageView"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:id="@+id/textView2"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true" />
如果我这样做是错的,请纠正我!
我可以findViewById()
但我无法设置文字(NullPointer
)。
从片段我甚至不能findViewById()
,即使它们在MainFragment
XML中。我搜索了很多,我找不到易于理解的解决方案或解释如何工作。提前谢谢!