[英]Access Fragment's TextView (inside a viewpager) from Activity
正如標題所說,我正在嘗試訪問(setText 等)片段內的 TextView。 該片段被加載到活動中的視圖頁面中。 我想從活動類訪問這個 TextView。
private PagerAdapter mPagerAdapter;
private ViewPager pager;
FragmentPageOne fragPageOne;
FragmentPageTwo fragPageTwo;
Activity 的 onCreate 執行:
fragPageOne= new FragmentPageOne();
fragPageTwo = new FragmentPageTwo();
mPagerAdapter = new ViewPagerAdapter(this, getSupportFragmentManager(),
fragPageOne.getClass(), fragPageTwo.getClass(),
);
pager = (ViewPager) findViewById(R.id.eventPager);
pager.setAdapter(mPagerAdapter);
ViewPagerAdapter 類:
public class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Class<? extends Fragment>> fragmentsClasses;
private final Context context;
public EventViewPagerAdapter(Context context, FragmentManager fm, Class<? extends Fragment>... fragmentsClasses) {
super(fm);
this.context = context;
this.fragmentsClasses = Arrays.asList(fragmentsClasses);
}
public Fragment getItem(int position) {
return Fragment.instantiate(context, fragmentsClasses.get(position).getName());
}
@Override
public int getCount() {
return fragmentsClasses.size();
}
}
FragmentPageOne 類(FragmentPageTwo 的結構類似):
public class FragmentPageOne extends Fragment {
public View rootView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if(container == null) {
return null;
}
rootView = inflater.inflate(R.layout.fragment_page_1, container, false);
return (LinearLayout) rootView;
}
}
當我嘗試使用它時(在活動本身內),我得到了一個空指針(顯然):
TextView text = (TexView) pager.findViewById(R.id.textview1);
text.setText("hello world);
獲取您當前的片段:
public Fragment getVisibleFragment(){
FragmentManager fragmentManager = this.getSupportFragmentManager();
List<Fragment> fragments = fragmentManager.getFragments();
if(fragments != null){
for(Fragment fragment : fragments){
if(fragment != null && fragment.isVisible())
return fragment;
}
}
return null;
}
然后從該視圖獲取片段的視圖以使用 findViewById。
您最好的選擇是在尋呼機適配器中的 instantiateItem 覆蓋方法中執行此操作;
private LayoutInflater layoutInflater;
private Activity activity;
private int[] layouts;
public WalletViewPagerAdapter(int[] layouts , Activity activity) {
this.activity = activity;
this.layouts =layouts;
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
layoutInflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(layouts[position], container, false);
if (position ==0) {
TextView availableBalance = view.findViewById(R.id.available);
availableBalance.setText("N100,0000,000");
}
container.addView(view);
return view;
}
您嘗試訪問的視圖在您調用它時尚不可用。 嘗試覆蓋 onViewCreated 方法,然后使用 view 參數像這樣獲取 textView ;
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
TextView availableBalance = view.findViewById(R.id.available);
availableBalance.setText("N100,0000,000");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.