Fragment "+ this +"not attached to Activity 예외 해결
public class TestFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
private TextView textView ;
private Handler handler = new Handler()
{
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
textView.setText(getString(R.string.app_name));
}
};
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment TestFragment.
*/
// TODO: Rename and change types and number of parameters
public static TestFragment newInstance(String param1, String param2) {
TestFragment fragment = new TestFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_test, container, false);
textView = (TextView)view.findViewById(R.id.test);
//
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
handler.sendEmptyMessage(1);
}
}).start();
return view;
}
// TODO: Rename method, update argument and hook method into UI event
@Override
public void onAttach(Context context) {
super.onAttach(context);
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
@Override
public void onDestroyView() {
super.onDestroyView();
// handler.removeCallbacksAndMessages(null);
/* handler.removeMessages(1);
handler.re*/
}
@Override
public void onDestroy() {
super.onDestroy();
handler.removeCallbacksAndMessages(null);
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
*
* See the Android Training lesson Communicating with Other Fragments for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
이 인터페이스에 들어가면 우리는 단지 네트워크가 시간을 소모하는 조작을 한 후에 메시지를 보내서 메인 인터페이스를 업데이트할 뿐인데 왜 붕괴되었을까?Google은 getString () 의 원본 코드를 보았습니다.
public final String getString(@StringRes int resId) {
return getResources().getString(resId);
}
getResources () 가 호출되고 아래를 봅니다.
final public Resources getResources() {
if (mHost == null) {
throw new IllegalStateException("Fragment " + this + " not attached to Activity");
}
return mHost.getContext().getResources();
}
mHost==null, 이 이상을 보고합니다. 인터페이스가 소각되면 mHost는null로 설정됩니다.그럼 이 문제를 어떻게 해결합니까?소스를 보면 다음과 같습니다.
/**
* Return true if the fragment is currently added to its activity.
*/
final public boolean isAdded() {
return mHost != null && mAdded;
}
이 방법은 mHost가 비어 있는지 판단하기 때문에 저희가 네트워크에서 요청을 한 후에 UI를 조작하기 전에 이 말을 덧붙여서 판단을 해서 붕괴 문제를 해결할 수 있습니다!
public class TestFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
private TextView textView ;
private Handler handler = new Handler()
{
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if(isAdded())//
textView.setText(getString(R.string.app_name));
}
};
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment TestFragment.
*/
// TODO: Rename and change types and number of parameters
public static TestFragment newInstance(String param1, String param2) {
TestFragment fragment = new TestFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_test, container, false);
textView = (TextView)view.findViewById(R.id.test);
//
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
handler.sendEmptyMessage(1);
}
}).start();
return view;
}
// TODO: Rename method, update argument and hook method into UI event
@Override
public void onAttach(Context context) {
super.onAttach(context);
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
@Override
public void onDestroyView() {
super.onDestroyView();
// handler.removeCallbacksAndMessages(null);
/* handler.removeMessages(1);
handler.re*/
}
@Override
public void onDestroy() {
super.onDestroy();
handler.removeCallbacksAndMessages(null);
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
*
* See the Android Training lesson Communicating with Other Fragments for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
OK, 문제 해결.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
SharedElementTransition with Navigation Architecture ComponentRecyclerView(일람 화면) -> 세부 화면 구성 SharedElementTransition 적용 Navigation Architecture Component에서 Fragment->Fragment 마이그레이션...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.