gpt4 book ai didi

android - 如果 EditText 不为空,是否可以在单击按钮时更改 fragment ?

转载 作者:行者123 更新时间:2023-11-30 02:09:12 24 4
gpt4 key购买 nike

我在加载 fragment 时有 MainActivityFrameLayout。假设在 MainActivity 中接下来有一个 Button,它加载下一个 fragment

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();
}

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

中有一些输入时,我才需要更改 fragment

我尝试使用 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 没有任何反应,如果我再次插入一些文本什么也没有,如果我启动应用程序并插入文本,按 next 它工作。

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

谢谢。

最佳答案

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
}
}

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");
}
}
}

关于android - 如果 EditText 不为空,是否可以在单击按钮时更改 fragment ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30348474/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com