【发布时间】:2015-02-05 17:46:54
【问题描述】:
我对称为表单活动的片段方法有疑问。 为了创建片段和调用方法,我使用位于 MainActivity.java 中的这个方法:
public void createFragment (int select, String string) {
switch (select) {
case 1:
ErrorFragment errorFragment = new ErrorFragment();
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragError, errorFragment)
.commit();
errorFragment = (ErrorFragment) getSupportFragmentManager().findFragmentById(R.id.fragError);
errorFragment.setText(string);
break;
case 2:
StringFragment stringFragment = new StringFragment();
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragString, stringFragment)
.commit();
stringFragment = (StringFragment) getSupportFragmentManager().findFragmentById(R.id.fragString);
stringFragment.setText(string);
break;
}
}
除了 textViews 和布局的名称之外,片段具有相同的布局和类。
ErrorFragment.java:
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class ErrorFragment extends Fragment {
public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_error,container,false);
}
public void setText(String text) {
TextView textView = (TextView) getActivity().findViewById(R.id.errorOut);
textView.setText(text);
}
}
fragment_error.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/errorTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/error"
android:textColor="#FF0000"
android:textSize="25sp"
android:gravity="center|top"/>
<TextView
android:id="@+id/errorOut"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:textSize="20sp"
android:text=""
android:gravity="center|top"/>
</LinearLayout>
createFragment() 被一些按钮调用
经过一些测试,我注意到片段已创建,但是当我调用“errorFragment.setText;”时应用程序崩溃。 在情况 2 中,应用程序不会崩溃,但不会显示 textview(我注意到如果我快速单击按钮,textView 会出现几毫秒)
编辑: 我试图这样做,但应用程序仍然崩溃
【问题讨论】:
标签: java android android-activity android-fragments