답변:
을 사용 getActivity()하면 a와 관련된 활동이 반환 fragment됩니다.
활동은 context ( Activity확장 이후 Context) 입니다.
getActivity().getApplicationContext()은 조각이 생성 될 때 인스턴스 변수에 값을 저장 한 다음 조각 클래스 내부에서 원할 때마다 해당 컨텍스트를 사용하는 것입니다. 그 맥락은 단편 분리에서도 살아남을 것입니다.
getActivity항상 사용 가능합니다. 그것은의 getContextAPI (23)에 추가 된
위의 답변으로 수행하기 위해 onAttach조각화 방법을 재정의 할 수 있습니다 .
public static class DummySectionFragment extends Fragment{
...
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
DBHelper = new DatabaseHelper(activity);
}
}
DatabaseHelper필요 하다면 ? 예를 들어, ...FragmentActivityActivityAdapter
onAttach(Activity activity)onDetach()
onAttach방법은 사용되지 않습니다Overrides deprecated method in 'android.support.v4.app.Fragment'
항상 getActivity () 메소드를 사용 하여 첨부 된 활동의 컨텍스트를 가져 오십시오. 그러나 한 가지만 기억하십시오. 프래그먼트는 약간 불안정하고 getActivity일부 경우 널을 리턴하므로 컨텍스트를 가져 오기 전에 항상 iPart () 메소드를 확인하십시오 getActivity().
내가 찾은 조각의 컨텍스트를 얻는 가장 쉽고 정확한 방법은 적어도 여기에서 메소드 ViewGroup를 호출 할 때 직접 가져 오는 것 onCreateView입니다 getActivity().
public class Animal extends Fragment {
Context thiscontext;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
thiscontext = container.getContext();
이전에 내가 사용하고 onAttach (Activity activity)얻을 수 context있는Fragment
문제
이 onAttach (Activity activity)메소드는 API 레벨 23에서 더 이상 사용되지 않습니다.
해결책
지금 상황을 얻기 위해 Fragment우리가 사용할 수 있습니다onAttach (Context context)
onAttach (Context context)
context. onCreate(Bundle)이 후에 호출됩니다.선적 서류 비치
/**
* Called when a fragment is first attached to its context.
* {@link #onCreate(Bundle)} will be called after this.
*/
@CallSuper
public void onAttach(Context context) {
mCalled = true;
final Activity hostActivity = mHost == null ? null : mHost.getActivity();
if (hostActivity != null) {
mCalled = false;
onAttach(hostActivity);
}
}
샘플 코드
public class FirstFragment extends Fragment {
private Context mContext;
public FirstFragment() {
// Required empty public constructor
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
mContext=context;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rooView=inflater.inflate(R.layout.fragment_first, container, false);
Toast.makeText(mContext, "THIS IS SAMPLE TOAST", Toast.LENGTH_SHORT).show();
// Inflate the layout for this fragment
return rooView;
}
}
우리는 또한 사용할 수 있습니다 getActivity()얻을 context에 Fragments
있지만 getActivity()반환 할 수 있습니다 null당신의이 경우 fragment현재 부모에 연결되어 있지 않습니다 activity,
Fragment 내부의 컨텍스트를 얻는 것은 getActivity()다음을 사용하여 가능합니다 .
public Database()
{
this.context = getActivity();
DBHelper = new DatabaseHelper(this.context);
}
Activity하여 프래그먼트와 관련된 것을 얻으려면 getActivity()사용할 수 있지만 메모리 누수를 유발하지 않는 것이 좋습니다.나는 더 나은 접근 방식 Activity이 onAttach()방법 에서 벗어나야한다고 생각합니다 .
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
context = activity;
}
Activity.findViewById이 액티비티의 등록 된 컨텐츠 뷰에서 뷰를 검색하는 편리한 방법 setContentView입니다. 올바른 예제에서 View.findViewById, not Activity.findViewById을 (를) 호출하고 올바른 루트보기 에서 메소드를 호출하고 있습니다. 완전히 다른 문제이며 분명히 해당 뷰를 보유하지 않는 뷰 계층에서 뷰를 찾을 수 없습니다.
Kotlin의 경우 context조각에 직접 사용할 수 있습니다 . 그러나 어떤 경우에는 다음과 같은 오류가 있습니다.
유형 불일치 : 유추 된 유형이 컨텍스트입니까? 그러나 상황은 예상되었다
이를 위해 당신은 이것을 할 수 있습니다
val ctx = context ?: return
textViewABC.setTextColor(ContextCompat.getColor(ctx, android.R.color.black))
Kotlin에서 API 29 이상을 사용 하여해야했습니다.
activity?.applicationContext!!
예를 들면
ContextCompat.getColor(activity?.applicationContext!!, R.color.colorAccent),
이상적으로는 전역을 사용할 필요가 없습니다. 조각에는 다른 알림이 있으며 그 중 하나는 onActivityCreated입니다. 프래그먼트의이 라이프 사이클 이벤트에서 활동 인스턴스를 확보 할 수 있습니다.
그런 다음 원하는대로 활동, 컨텍스트 또는 애플리케이션 컨텍스트를 얻기 위해 프래그먼트를 역 참조 할 수 있습니다.
this.getActivity()액티비티에
this.getContext()대한 핸들을 제공하고 컨텍스트에
this.getActivity().getApplicationContext()대한 핸들을 제공하여 애플리케이션 컨텍스트에 대한 핸들을 제공합니다. 응용 프로그램 컨텍스트를 db로 전달할 때 응용 프로그램 컨텍스트를 사용하는 것이 좋습니다.
간단한 방법은을 사용하는 것 getActivity()입니다. 그러나 getActivity()컨텍스트를 얻기 위해 메소드를 사용하는 데 대한 혼란은 널 포인터 예외 라고 생각합니다 .
이를 위해 먼저 isAdded()추가 여부를 결정 하는 방법을 확인한 다음를 사용하여 getActivity()Activity의 컨텍스트를 얻을 수 있습니다 .
getActivity () 메소드를 사용하여 컨텍스트를 가져 오거나 getContext () 메소드를 사용할 수 있습니다.
View root = inflater.inflate(R.layout.fragment_slideshow, container, false);
Context c = root.getContext();
도움이 되길 바랍니다!
public class MenuFragment extends Fragment implements View.OnClickListener {
private Context mContext;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
FragmentMenuBinding binding=FragmentMenuBinding.inflate(inflater,container,false);
View view=binding.getRoot();
mContext=view.getContext();
return view;
}
}
getActivity 오류를 사용할 때 arrayAdapter IN 조각을 사용하기위한 컨텍스트가 필요 하지만 getContext로 바꾸면 나에게 효과적입니다.
listView LV=getView().findViewById(R.id.listOFsensors);
LV.setAdapter(new ArrayAdapter<String>(getContext(),android.R.layout.simple_list_item_1 ,listSensorType));
getActivity()또는 getContext조각으로 사용할 수 있습니다 .선적 서류 비치
/**
* Return the {@link FragmentActivity} this fragment is currently associated with.
* May return {@code null} if the fragment is associated with a {@link Context}
* instead.
*
* @see #requireActivity()
*/
@Nullable
final public FragmentActivity getActivity() {
return mHost == null ? null : (FragmentActivity) mHost.getActivity();
}
과
/**
* Return the {@link Context} this fragment is currently associated with.
*
* @see #requireContext()
*/
@Nullable
public Context getContext() {
return mHost == null ? null : mHost.getContext();
}
항상 확인 if(getActivity!=null)하기 때문에 이 널 (null) 일 수있다 단편 활동에 연결되지 않은 경우. 때로는 나머지 API에서 데이터를 가져 오는 것과 같이 조각에서 긴 작업을 수행하는 데 시간이 걸립니다. 사용자가 다른 조각으로 이동하는 경우 그러면 getActivity가 널이됩니다. 처리하지 않으면 NPE를 받게됩니다.
FragmentHostCallback클래스의 인스턴스입니다 .
kotlin 샘플의 내부 조각은 누군가를 도울 것입니다.
textViewStatus.setTextColor(ContextCompat.getColor(context!!, R.color.red))
데이터 바인딩을 사용하는 경우
bindingView.textViewStatus.setTextColor(ContextCompat.getColor(context!!, R.color.red))
다음 과 같이 onCreateView 에서 bindingView가 초기화됩니다.
private lateinit var bindingView: FragmentBookingHistoryDetailBinding
bindingView = DataBindingUtil.inflate(inflater, R.layout.your_layout_xml, container, false)
requireContext () 메소드가 가장 간단한 옵션입니다
requireContext()
예
MyDatabase(requireContext())