晚安!
我正在Android Studio
中开发一个小型应用程序,以测试与SoftKeyboard
相关的各种功能。
我的应用程序中的Activity
中包含一个Fragment
和两个Activity
。
第二个Fragment
无关紧要,因此它为空。
第一个片段包含一个EditText
,一个RecyclerView
(将不包含任何数据)和一个ProgressBar
。
我要寻找的行为是,当您单击EditText
时,将打开SoftKeyboard
。此时,如果用户离开应用程序并重新输入,我希望SoftKeyboard
保持可见。
否则,如果在应用程序处于前台时EditText
没有焦点,我希望SoftKeyboard
不可见,并且当用户关闭并重新打开应用程序时,{{1 }}不应出现。
另一方面;当用户单击与SoftKeyboard
关联并通过EditText
显示的确认按钮时,我希望SoftKeyboard
可见,但仅在{{1 }}无需考虑键盘所占用的空间,因为否则此ProgressBar
将从初始位置(键盘处于打开状态)移动到最终位置(Activity
关闭时),我不想那样的效果。
PD1 :请不要将我引至其他StackOverflow页面,因为我已对它们全部进行了分析,但它们都不适合我。
PD2 :不要考虑我已将图像中XML格式文件的代码放入图像中。我花了45分钟试图将代码作为文本输入,但我一直摆脱缩进错误。
希望您能帮助我,在此先感谢您。
MainActivity:
ProgressBar
片段1:
SoftKeyboard
activity_main.xml :
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager viewPager = findViewById(R.id.viewPager);
setupViewPager(viewPager);
TabLayout TabLayout = findViewById(R.id.tabs);
TabLayout.setupWithViewPager(viewPager);
}
private void setupViewPager(ViewPager viewPager) {
SectionsPageAdapter adapter = new SectionsPageAdapter(getSupportFragmentManager());
adapter.addFragment(new Fragment1(), "Fragment1");
adapter.addFragment(new Fragment(), "Fragment2");
viewPager.setAdapter(adapter);
}
}
fragment_1.xml:
public class Fragment1 extends Fragment {
private EditText mSearchEditText;
private ProgressBar mProgressBar;
private RecyclerView mRecyclerView;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_1, container, false);
mSearchEditText = view.findViewById(R.id.search_edit_text);
mSearchEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
hideSoftKeyboard(getActivity());
mProgressBar.setVisibility(View.VISIBLE);
return true;
}
return false;
}
});
mRecyclerView = view.findViewById(R.id.recycler_view);
mProgressBar = view.findViewById(R.id.progress_bar);
return view;
}
public void hideSoftKeyboard(Activity activity) {
if (activity.getCurrentFocus() == null) {
return;
}
InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
assert inputMethodManager != null;
inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
}
}
答案 0 :(得分:0)
您可以简单地使用单独的标志(带有条件的布尔变量)并为软键盘放置检查条件(使用预定义标志,例如true或false)。
在主要活动中。
@Override
protected void onResume() {
super.onResume();
// enter some conditions here
}
当应用程序进入后台时,将调用onPause和onResume方法。要了解更多信息,请贯穿整个活动生命周期。