我正在尝试使用搜索栏,以便用户可以调整片段中edittext框的值。这是我使用它的地方:
...
//NOTE: This is in the onCreateView() method for a Fragment
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
seekBar.setProgress(seekBar.getProgress() + 1);
editText.setText(String.valueOf(seekBar.getProgress()));
//Hidden method call not needed to be visible...
//Notice the InputMethodManager, also, this is line 197...
InputMethodManager imm = (InputMethodManager) context.getSystemService(
Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(seekBar.getWindowToken(), 0);
}
});
...
这是Logcat输出:
03-09 00:00:41.164 573-573/com.hidden.hidden E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at com.hidden.hidden.hidden.onClick(Hidden.java:197)
at android.view.View.performClick(View.java:3480)
at android.view.View$PerformClick.run(View.java:13983)
at android.os.Handler.handleCallback(Handler.java:605)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4340)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
请注意,出于安全原因,软件包名称是隐藏的。
感谢任何帮助!
编辑:请注意,在第197行,我没有“上下文”。那里。它给了我和错误,所以我声明了一个像这样的全局变量:Context context;
答案 0 :(得分:5)
试试这个
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
seekBar.setProgress(seekBar.getProgress() + 1);
editText.setText(String.valueOf(seekBar.getProgress()));
try{
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(
Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(seekBar.getWindowToken(), 0);
}catch(Exception e){
e.printStackTrace();
}
}
});
给我反馈意见。
答案 1 :(得分:0)
Context context = getActivity(); //since you're in a fragment
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
seekBar.setProgress(seekBar.getProgress() + 1);
editText.setText(String.valueOf(seekBar.getProgress()));
InputMethodManager imm = (InputMethodManager) context.getSystemService(
Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(seekBar.getWindowToken(), 0);
}
});
编辑:请勿在{{1}}之前致电getActivity()
。否则它将返回null。