프래그먼트 내의 컨텍스트 사용
콘텍스트를 fragment로 가져오려면 어떻게 해야 하나요?
를 받아들이는 해야 하는데, 이 는 다음과 같습니다getApplicationContext()
★★★★★★★★★★★★★★★★★」FragmentClass.this
하지지 않는? ???
데이터베이스 생성자
public Database(Context ctx)
{
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
를 사용하면 에 관련된 액티비티가 반환됩니다.fragment
.
는 ★★★★★★★★★★★★★★★★★」context
( since extends.
, 은 이 문제를 수 .onAttach
다음 중 하나:
public static class DummySectionFragment extends Fragment{
...
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
DBHelper = new DatabaseHelper(activity);
}
}
가장 은 fragment fragment에서 직접 입니다.ViewGroup
했을 때onCreateView
적어도 은 null이 .getActivity()
:
public class Animal extends Fragment {
Context thiscontext;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
thiscontext = container.getContext();
항상 getActivity() 메서드를 사용하여 연결된 액티비티의 콘텍스트를 가져옵니다.단, fragment는 약간 불안정하고getActivity
null을 반환하는 경우도 있기 때문에, 그 경우는, 콘텍스트를 취득하기 전에, 항상 fragment의 isAdded() 메서드를 체크해 주세요.getActivity()
.
를 사용하고 있습니다.onAttach (Activity activity)
context
Fragment
문제
이 메서드는 API 수준 23에서 더 이상 사용되지 않습니다.
솔루션
이번에는 .Fragment
사용할 수 있다
onAttach (Context context)
- 가 fragment에 되었을 때 됩니다.
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;
}
}
메모
또, 를 사용해context
Fragments
getActivity()
할 수 있다null
의 만 if if if if가fragment
않습니다.activity
,
@Override
public void onAttach(Activity activity) {
// TODO Auto-generated method stub
super.onAttach(activity);
context=activity;
}
올바른 방법은
requireContext()
및 예시
ContextCompat.getColor(requireContext(), R.color.colorAccent),
require Context() 메서드는 가장 간단한 옵션입니다.
requireContext()
예
MyDatabase(requireContext())
는 ,, 이, 이, 이에서도 얻을 수 .inflater
""를 경우 ""를 덮어씁니다.onCreateView
.
public static class MyFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
/* ... */
Context context = inflater.getContext();
/* ... */
}
}
또 다른 접근방식은 다음과 같습니다.
콘텍스트는, 다음의 방법으로 취득할 수 있습니다.
getActivity().getApplicationContext();
fragment내의 콘텍스트를 취득하려면 , 다음의 순서에 따릅니다.
public Database()
{
this.context = getActivity();
DBHelper = new DatabaseHelper(this.context);
}
- 조심해요.
Activity
fragment를 사용하여 .getActivity()
를 사용할 수 있지만 메모리 누수의 원인이 되는 것은 권장하지 않습니다.
은 '를 얻는 에 틀림없어요.Activity
onAttach()
★★★★
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
context = activity;
}
getContext()
API 23 로 api 。getActivity()로 지정합니다.
에러가 해결되는지 확인합니다.대상 API 레벨과 최소 API 레벨 사이에 있는 메서드를 사용해 보십시오.그렇지 않으면 이 오류가 발생합니다.
이 있기 에 API 레벨 23이 .getContext()
, 하려면 ""를 합니다.getActivity().getApplicationContext()
지원 버전을 사용할 것을 권장합니다.Fragment
어느 것이android.support.v4.app.Fragment
.
Kotlin의 경우 사용할 수 있습니다.context
직접 조각조각으로.그러나 일부 상자에서는 다음과 같은 오류를 발견할 수 있습니다.
유형 불일치: 유추된 유형이 컨텍스트입니까?그러나 컨텍스트는 예상되었습니다.
그렇기 때문에 당신은 이것을 할 수 있다.
val ctx = context ?: return
textViewABC.setTextColor(ContextCompat.getColor(ctx, android.R.color.black))
getActivity()
콘텍스트의 하위 항목이기 때문에, 이것은 당신에게 도움이 될 것입니다.
지원 라이브러리의 단편 사용 -
android.support.v4.app.Fragment
그 후 오버라이드
void onAttach (Context context) {
this.context = context;
}
이렇게 하면 컨텍스트는 항상 null이 아닌 값이 됩니다.
다양한 옵션이 있습니다.
- minSDK < = 21인 경우,
getActivity()
이 경우는,Context
. - minSDK가 >=23인 경우 를 사용할 수 있습니다.
getContext()
.
이전 버전을 지원할 필요가 없는 경우 다음 절차를 따릅니다.getContext()
.
코틀린에서는 그냥 사용하세요.activity
대신getActivity()
getActivity() 메서드를 사용하여 컨텍스트를 가져오거나 getContext() 메서드를 사용할 수 있습니다.
View root = inflater.inflate(R.layout.fragment_slideshow, container, false);
Context c = root.getContext();
도움이 됐으면 좋겠네요!
콘텍스트를 프래그먼트화하는 안전한 방법
if(isAdded){
requireActivit();//this is your context
}
이상적으로는 글로벌을 사용할 필요가 없습니다.fragment에는 다른 알림이 있습니다.그 중 하나는 onActivityCreated입니다.프래그먼트의 이 라이프 사이클이벤트에서 액티비티의 인스턴스를 취득할 수 있습니다.
그런 다음 fragment를 참조 해제하여 원하는 액티비티, 컨텍스트 또는 애플리케이션 컨텍스트를 얻을 수 있습니다.
this.getActivity()
액티비티의 핸들을 당신에게 넘겨줄 것이다.this.getContext()
문맥을 파악할 수 있습니다.this.getActivity().getApplicationContext()
는 어플리케이션 컨텍스트에 대한 핸들을 제공합니다.응용 프로그램콘텍스트를 db로 전달할 때 사용하는 것이 좋습니다.
은 '우리'를 사용하는 입니다.getActivity()
하지만, 제 생각에, 이 제품을 사용하는 것의 큰 혼란은getActivity()
여기서 컨텍스트를 가져오는 메서드는 null 포인터 예외입니다.
위해 ""에 합니다.isAdded()
여부를 하는 방법, 그에 '추가를 사용할 수 .getActivity()
이치노
요.getActivity()
그 중에서도,
public void onAttach(Context context) {
super.onAttach(context);
this.activity = (CashActivity) context;
this.money = this.activity.money;
}
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;
}
}
쓸 수 있을 것 같아요.
public static class MyFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Context context = getActivity.getContext();
}
}
arrayAdapter IN fragment를 사용하기 위한 컨텍스트가 필요합니다.getActivity 에러가 발생하지만 getContext로 대체하면 효과가 있습니다.
listView LV=getView().findViewById(R.id.listOFsensors);
LV.setAdapter(new ArrayAdapter<String>(getContext(),android.R.layout.simple_list_item_1 ,listSensorType));
네 위에서 fragment
((Name_of_your_Activity) getActivity()).helper
액티비티 중
DbHelper helper = new DbHelper(this);
코틀린 샘플의 내부 조각이 누군가를 도울 것입니다.
textViewStatus.setTextColor(ContextCompat.getColor(context!!, R.color.red))
데이터 바인딩을 사용하는 경우
bindingView.textViewStatus.setTextColor(ContextCompat.getColor(context!!, R.color.red))
여기서 bindingView는 onCreateView에서 다음과 같이 초기화됩니다.
private lateinit var bindingView: FragmentBookingHistoryDetailBinding
bindingView = DataBindingUtil.inflate(inflater, R.layout.your_layout_xml, container, false)
getActivity()를 사용하면 fragment와 관련된 액티비티가 반환됩니다.액티비티는 컨텍스트입니다(액티비티가 컨텍스트를 확장하므로).
주의: getActivity()는 각 fragment의 onAttach 전에 호출된 경우 null을 반환할 수 있습니다.
2.or
발견된 fragment의 콘텍스트를 취득하는 가장 쉽고 정확한 방법은 적어도 여기서 onCreateView메서드를 호출할 때 ViewGroup에서 직접 취득하는 것입니다.getActivity()의 null은 취득하지 않습니다.
public class Animal extends Fragment {
Context thiscontext;
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState)
{
thiscontext = container.getContext();
//...
//...
//...
}
Kotlin에서는 requireActivity().applicationContext 를 사용할 수 있습니다.
언급URL : https://stackoverflow.com/questions/8215308/using-context-in-a-fragment
'programing' 카테고리의 다른 글
Panda GroupBy를 사용하여 각 그룹(수, 평균 등)에 대한 통계를 얻으시겠습니까? (0) | 2022.10.21 |
---|---|
C 또는 C++에서 문자열을 되돌리려면 어떻게 해야 합니까? (0) | 2022.10.21 |
Objective-C에서의 선언 및 체크/비교(비트마스크-) Enum (0) | 2022.10.21 |
#1064 - SQL 구문에 오류가 있습니다.MariaDB 서버 버전에 대응하는 매뉴얼에서 사용하는 올바른 구문을 확인해 주십시오.근접적인 이유는 무엇입니까? (0) | 2022.10.21 |
Django 옵션 URL 파라미터 (0) | 2022.10.21 |