尝试从片段中的editText获取Text时发生ViewPager错误

时间:2018-10-29 13:20:31

标签: android android-fragments nullpointerexception android-viewpager

我的viewPager具有相同的片段。在每个片段中,我只有一个editText,我想从edit获取字符串。当我尝试执行此操作时,我有空指针。

我有此代码:

ViewPager的适配器:

public class SamplePagerAdapter extends FragmentPagerAdapter {
private int size;

public SamplePagerAdapter(FragmentManager fm, int size) {
    super(fm);
    this.size = size;
}

@Override
public Fragment getItem(int position) {
    FragmentForNamePlayers fragment = new FragmentForNamePlayers();
    hashCode();
    return fragment;
}

@Override
public int getCount() {
    return size;
}}

片段:

public class FragmentForNamePlayers extends Fragment implements FragmentLifecycle  {
private EditText editText;
View rootView;

public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
     rootView = inflater.inflate(R.layout.players_name_for_fragment,
            container, false);
    editText=rootView.findViewById(R.id.edForNamePlayers);
    return rootView;
}
@Override
public void onPause() {
    super.onPause();
}
@Override
public void onChangeEditTExt() {
    String s=editText.getText().toString();
}}

活动: 当我在viewPager中滑动到下一个片段时,我的界面会尝试从片段中的editText获取文本,在此刻我的应用会出错

public class PopupPlayersName extends AppCompatActivity   {
private  int widht;
private  int height;
private SharedPreferences preferences;
private ViewPager viewPager;
private TextView back;
private TextView cancel;
private TextView next;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.name_players_popup);

    viewPager=findViewById(R.id.ViewPager);
    back=findViewById(R.id.buttonBack);
    cancel=findViewById(R.id.buttonCancel);
    next=findViewById(R.id.buttonNext);

    DisplayMetrics metrics=new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(metrics);
    widht=metrics.widthPixels;
    height=metrics.heightPixels;
    getWindow().setLayout((int)(widht*.8),(int)(height*.4));
    preferences=getSharedPreferences(MainActivity.REQUEST_CODE_SHARED,MODE_PRIVATE);
    final int count=preferences.getInt(MainActivity.REQUEST_CODE_SHARED,-1);

    final SamplePagerAdapter adapter=new SamplePagerAdapter(getSupportFragmentManager(),count);
     ViewPager.OnPageChangeListener pageChangeListener = new ViewPager.OnPageChangeListener() {
        int currentPosition = 0;
        @Override
        public void onPageSelected(int newPosition) {
            FragmentLifecycle fragmentToHide = (FragmentLifecycle)adapter.getItem(currentPosition);
            fragmentToHide.onChangeEditTExt();
            currentPosition = newPosition;
        }
        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) { }

        public void onPageScrollStateChanged(int arg0) { }
    };
    viewPager.setAdapter(adapter);
    viewPager.setCurrentItem(0);
    viewPager.addOnPageChangeListener(pageChangeListener);

    back.setTextColor(getResources().getColor(R.color.grey));
    back.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int temp=viewPager.getCurrentItem();
            if(temp==1){
                back.setTextColor(getResources().getColor(R.color.grey));
            }
            if(temp!=0){
                viewPager.setCurrentItem(temp-1,true);
            }
                next.setTextColor(getResources().getColor(R.color.colorAccent));
        }
    });
    cancel.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            finish();
        }
    });
    next.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int temp=viewPager.getCurrentItem();
            if(temp==count-2){
                next.setTextColor(getResources().getColor(R.color.grey));
            }
                back.setTextColor(getResources().getColor(R.color.colorAccent));
            if(temp!=count-1){
                viewPager.setCurrentItem(temp+1,true);
            }
        }
    });
}}

和我的界面:

public interface FragmentLifecycle {
   void onChangeEditTExt();
}

例外:

10-29 08:55:42.544 4937-4937/com.glasha.nuar E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.glasha.nuar, PID: 4937
    java.lang.NullPointerException
        at com.glasha.nuar.fragments.FragmentForNamePlayers.onChangeEditTExt(FragmentForNamePlayers.java:36)
        at com.glasha.nuar.activities.PopupPlayersName$1.onPageSelected(PopupPlayersName.java:60)
        at android.support.v4.view.ViewPager.dispatchOnPageSelected(ViewPager.java:1941)
        at android.support.v4.view.ViewPager.scrollToItem(ViewPager.java:680)
        at android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:664)
        at android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:625)
        at android.support.v4.view.ViewPager.setCurrentItem(ViewPager.java:617)
        at com.glasha.nuar.activities.PopupPlayersName$4.onClick(PopupPlayersName.java:100)

1 个答案:

答案 0 :(得分:0)

在您的SamplePagerAdapter班上。

@Override
public Fragment getItem(int position) {
    FragmentForNamePlayers fragment = new FragmentForNamePlayers();
    hashCode();
    return fragment;
}

每次用户在ViewPager上的页面之间切换时,都会创建FragmentForNamePlayers的新实例。

@Override
public void onPageSelected(int newPosition) {
    FragmentLifecycle fragmentToHide = (FragmentLifecycle)adapter.getItem(currentPosition);
    fragmentToHide.onChangeEditTExt();
    currentPosition = newPosition;
}

从您的代码中,当用户滑动到下一页时,您会在上一页调用onChangeEditTExt,但那时会创建上一页的新实例,但是onCreateView总是在{{ 1}}。这就是为什么您的应用程序总是崩溃的原因。

解决方案::重复使用在给定位置创建的片段,否则创建一个新片段。

SamplePagerAdapter

onChangeEditTExt