我的应用因TextView
而崩溃。只要设备不改变其方向,它就可以工作。如果我删除TextView并旋转设备一切正常,但使用TextView则没有
我有2个纵向和布局的布局。
它们看起来像那样:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<TextureView
android:id="@+id/texture"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<TextView
android:layout_width="220dp"
android:layout_height="50dp"
android:id="@+id/text_time"
android:textSize="20dp"
android:textColor="@color/red"
android:layout_marginTop="14dp"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>
还有一些代码:
public void onViewCreated(final View view, Bundle savedInstanceState) {
mTextView = (TextView) view.findViewById(R.id.text_time);
mTextView.setVisibility(View.INVISIBLE);
}
然后在另一种方法中设置文本:
mTextView.setVisibility(View.VISIBLE);
mTextView.setText("Text");
就是这样。那么你有什么建议吗?
我收到以下错误:
01-07 17:14:28.117 12890-12890/k.com.kamera E/AndroidRuntime: FATAL EXCEPTION: main
Process: k.com.kamera, PID: 12890
java.lang.IllegalStateException: Fragment BasicFragmentVideo{e87fd0c} not attached to Activity
at android.app.Fragment.getResources(Fragment.java:805)
at android.app.Fragment.getString(Fragment.java:840)
at k.com.kamera.BasicFragmentVideo$5$1$1.run(BasicFragmentVideo.java:483)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:168)
at android.app.ActivityThread.main(ActivityThread.java:5845)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:797)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:687)
答案 0 :(得分:0)
每次方向改变时,您都在创建一个新的Fragment实例。并且其中只有一个实际上附加到Activity。试试这个
public class TestActivity extends Activity {
TestFragment testFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test_activity);
attachFragment(savedInstanceState);
}
private void attachFragment(Bundle savedInstanceState) {
if (savedInstanceState == null){
testFragment = new TestFragment();
getFragmentManager().beginTransaction()
.replace(R.id.camera_frame, testFragment, "testFragment").commitAllowingStateLoss();
} else {
testFragment = (TestFragment)getFragmentManager().findFragmentByTag("testFragment");
}
}
在您的片段setRetainInstance(true)
()或onCreateView
()
onActivityCreated
答案 1 :(得分:0)
在片段中使用setRetainInstance为true,这将在方向发生时保留片段实例,现在在Acitivty里面onCreate检查你的片段实例并添加