如果EditText不为空,可以在按钮上单击更改片段吗?

时间:2015-05-20 11:33:44

标签: android android-fragments

我有MainActivityFrameLayout我加载片段。 可以说,在MainActivity中,下一个Button会加载下一个片段

public void btnNextClick(View view) {
    Fragment currentFragment;
    currentFragment = new F2Fragment();
    FragmentManager fm = getFragmentManager();
    FragmentTransaction fragmentTransaction = fm.beginTransaction();
    fragmentTransaction.replace(R.id.fragment_switch, currentFragment);
    fragmentTransaction.commit();
}

此部分会将下一个片段加载到屏幕(在本例中为f2Fragment) 在第一个片段(f1Fragment)里面我有EditText字段,只有在EditText

中有一些输入时才需要更改片段

我尝试使用SharedPreferences

pref=activity.getSharedPreferences("default", 0);
edt = pref.edit();
public void onPause() {
   super.onPause();          
   edt.putString("edtText",edtText.getText().toString()).apply();
}

稍后在MainActivity我尝试了解并检查长度

public void btnNextClick(View view) {
      pref = this.getSharedPreferences("default",0);
      String edtText = pref.getString("edtText","");
      if(edtText.length()>0){
          Fragment currentFragment;
          currentFragment = new F2Fragment();
          FragmentManager fm = getFragmentManager();
          FragmentTransaction fragmentTransaction = fm.beginTransaction();
          fragmentTransaction.replace(R.id.fragment_switch,currentFragment);
          fragmentTransaction.commit();
      }
}

这仅适用于第一次,如果我保持编辑空白并按next没有任何反应,如果我再插入一些文本,如果我启动应用程序并插入文本,请按下它工作。

如果我有两个需要检查的编辑怎么办?

谢谢。

1 个答案:

答案 0 :(得分:1)

public class ActivityActivityTablet extends Activity implements      FragmentA.OnEditBoxTextLoadNewFragment{
.
.
.
//other Activity methods and your code
.
.

@Override
  public void OnEditBoxTextLoadNewFragment(String textFromFragA) {
//load new fragment//if else will work if you need more than loading the     fragment
  }
}

片段应该是这样的:

public class ActivityFragment extends Fragment {
private OnEditBoxTextLoadNewFragment mListener;

//other fragment code of yours

 public interface OnEditBoxTextLoadNewFragment{
     public void OnEditBoxTextLoadNewFragment(String edit text);
 }

 EditText text= (EditText) findViewById(R.id.text1);
    text1.addTextChangedListener(new TextWatcher() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                int count) {


            if (!s.toString().equalsIgnoreCase("")) {
                mListener.OnEditBoxTextLoadNewFragment(s);
            } 

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
        }

        @Override
        public void afterTextChanged(Editable s) {
        }
    });
   @Override
   public void onAttach(Activity activity) {
       super.onAttach(activity);
    try {
        mListener = (OnEditBoxTextLoadNewFragment) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString()
                + " must implement OnEditBoxTextLoadNewFragment");
    }
  }
}