我有一个TextView
,我希望得到一些特定行的文字,但是当我使用txt.getLayout.getLineStart(1)
时,它会返回null并导致应用崩溃,这是什么原因?
TextView txt = (TextView)mRootView.findViewById(R.id.txt);
int start = txt.getLayout().getLineStart(1);
int end = txt.getLayout().getLineEnd(1);
String first = txt.getText().subSequence(start,end).toString();
崩溃日志
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.sattva.animalsencyclopedia, PID: 11244
java.lang.NullPointerException
at com.sattva.animalsencyclopedia.fragments.FragmentInformation.onViewCreated(FragmentInformation.java:110)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1086)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1252)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1617)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:517)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5333)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:829)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:645)
at dalvik.system.NativeStart.main(Native Method)
答案 0 :(得分:1)
可能您没有以正确的方式使用findViewById()
方法找到此视图。您正在使用片段,可能您有类似getActivity().findViewById()
的内容。尝试使用onCreateView()
方法执行类似view.findViewById()
的操作,其中view
是膨胀的结果。
正如@pskink在文档中提到的那样:returns Layout the Layout that is currently being used to display the text. This can be null if the text or width has recently changes.
尝试在onStart或onCreate方法中调用此代码,但是您应该将txt
作为类成员变量。
int start = txt.getLayout().getLineStart(1);
int end = txt.getLayout().getLineEnd(1);
String first = txt.getText().subSequence(start,end).toString();