从Activity访问Fragment的TextView(在viewpager中)

时间:2016-08-02 18:21:45

标签: android android-fragments nullpointerexception android-viewpager textview

正如标题所说,我试图访问(setText等)片段内的TextView。片段被加载到活动中的viewpager中。我想从活动类中访问此TextView。

private PagerAdapter mPagerAdapter;
private ViewPager pager;
FragmentPageOne fragPageOne;
FragmentPageTwo fragPageTwo;

发布活动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);

3 个答案:

答案 0 :(得分:0)

获取您当前的片段:

 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。

答案 1 :(得分:0)

您最好的选择是像这样在寻呼机适配器的InstantiateItem覆盖方法中执行此操作;

let a = 10;
let b = 10;
let c = 10;

答案 2 :(得分:0)

您正在尝试访问的视图在您调用它时尚不可用。尝试覆盖onViewCreated方法,然后使用view参数获取textView;

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {

TextView availableBalance = view.findViewById(R.id.available);
        availableBalance.setText("N100,0000,000");

}