Używanie kontekstu we fragmencie
Jak mogę uzyskać kontekst we fragmencie?
Muszę użyć mojej bazy danych, której konstruktor bierze w kontekście, ale getApplicationContext()
i FragmentClass.this
nie działają więc co mogę zrobić?
Konstruktor bazy danych
public Database(Context ctx)
{
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
23 answers
Możesz użyć getActivity()
, który zwraca aktywność związaną z fragmentem.
Działanie jest kontekstem (ponieważ działanie rozszerza kontekst) .
Aby wykonać powyższą odpowiedź, możesz nadpisać metodę onAttach
fragmentu:
public static class DummySectionFragment extends Fragment{
...
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
DBHelper = new DatabaseHelper(activity);
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-07-29 03:47:17
Zawsze używaj metody getActivity(), Aby uzyskać kontekst dołączonej aktywności, ale zawsze pamiętaj o jednym: fragmenty są nieco niestabilne i getActivity
zwraca null kilka razy, więc w tym celu zawsze sprawdzaj metodę isAdded () fragmentu przed pobraniem kontekstu przez getActivity()
.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-01-31 17:15:51
Najprostszym i najbardziej precyzyjnym sposobem uzyskania kontekstu fragmentu, który znalazłem, jest uzyskanie go bezpośrednio z ViewGroup
Kiedy wywołujesz metodę onCreateView
przynajmniej tutaj jesteś pewien, że nie dostaniesz null dla getActivity()
:
public class Animal extends Fragment {
Context thiscontext;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
thiscontext = container.getContext();
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-09-09 19:44:21
@Override
public void onAttach(Activity activity) {
// TODO Auto-generated method stub
super.onAttach(activity);
context=activity;
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-06-17 06:00:58
Uzyskanie kontekstu wewnątrz fragmentu będzie możliwe za pomocą getActivity()
:
public Database()
{
this.context = getActivity();
DBHelper = new DatabaseHelper(this.context);
}
- bądź ostrożny, aby uzyskać
Activity
skojarzony z fragmentem za pomocągetActivity()
, możesz go użyć, ale nie jest to zalecane, spowoduje to wycieki pamięci.
Myślę, że lepszym aprochem musi być uzyskanie {[3] } z metody onAttach()
:
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
context = activity;
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-03-02 16:05:35
Inne alternatywne podejście to:
Możesz uzyskać kontekst używając:
getActivity().getApplicationContext();
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-01-31 17:16:35
Możesz również pobrać kontekst z parametru inflater
, gdy nadpisujesz onCreateView
.
public static class MyFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
/* ... */
Context context = inflater.getContext();
/* ... */
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-11-19 05:39:40
getContext()
zajął 23. Zastąp ją getActivity () wszędzie w kodzie.
Sprawdź, czy naprawia błąd. Spróbuj użyć metod, które znajdują się pomiędzy poziomem docelowym a minimun API, w przeciwnym razie pojawi się ten błąd.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-01-31 17:26:40
Od poziomu API 23 istnieje getContext()
, ale jeśli chcesz obsługiwać starsze wersje, możesz użyć getActivity().getApplicationContext()
, podczas gdy ja nadal zalecam korzystanie z wersji wsparcia Fragment
, która jest android.support.v4.app.Fragment
.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-06-19 09:57:38
getActivity()
jest dzieckiem kontekstu, więc powinno działać dla ciebie
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-11-09 21:37:32
Masz różne opcje:
- Jeśli twój minSDK getActivity(), ponieważ jest to
Context
. - Jeśli twój minSDK wynosi > =23, możesz użyć
getContext()
.
Jeśli nie musisz obsługiwać starych wersji, Wybierz getContext()
.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-04-01 13:45:46
Dla Kotlina można używać context
bezpośrednio we fragmentach. Ale w niektórych przypadkach znajdziesz błąd jak
Type mismatch: inferred type is Context? ale oczekiwano kontekstu
Za to możesz to zrobić
val ctx = context ?: return
textViewABC.setTextColor(ContextCompat.getColor(ctx, android.R.color.black))
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-02-08 12:41:46
Najlepiej, aby nie trzeba było używać globals. Fragment ma różne powiadomienia, z których jeden jest onActivityCreated. Wystąpienie aktywności można uzyskać w tym zdarzeniu cyklu życia fragmentu.
Następnie: możesz dereferować fragment, aby uzyskać activity, context lub applicationcontext, jak chcesz:
this.getActivity()
da ci uchwyt do działania
this.getContext()
da ci uchwyt do kontekstu
this.getActivity().getApplicationContext()
da ci uchwyt do kontekstu aplikacji. Powinieneś najlepiej użyć kontekstu aplikacji podczas przekazywania go do db.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-11-27 05:32:37
Prostym sposobem jest użycie getActivity()
. Ale myślę, że głównym błędem w używaniu metody getActivity()
do uzyskania kontekstu jest wyjątek wskaźnika null.
W tym celu najpierw sprawdź za pomocą metody isAdded()
, która określi, czy została dodana, czy nie, a następnie możemy użyć getActivity()
, aby uzyskać kontekst aktywności.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-01-31 17:24:20
Użyj fragmentów z Support Library -
android.support.v4.app.Fragment
A następnie nadpisać
void onAttach (Context context) {
this.context = context;
}
W ten sposób możesz być pewien, że context zawsze będzie wartością inną niż null.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-02-14 09:32:35
Metoda GetContext () pomaga użyć kontekstu klasy w aktywności fragmentu.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-01-20 07:20:28
Możesz zadzwonić getActivity()
lub,
public void onAttach(Context context) {
super.onAttach(context);
this.activity = (CashActivity) context;
this.money = this.activity.money;
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-04-01 09:07:54
Myślę, że możesz użyć
public static class MyFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Context context = getActivity.getContext();
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-08 09:27:31
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;
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-03 12:19:20
Możesz również użyć:
inflater.getContext();
Ale wolałbym użyć
getActivity()
Lub
getContext
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-15 18:36:44
Potrzebuję kontekstu do używania arrayAdapter w fragmencie, gdy używałem getActivity pojawia się błąd, ale gdy zamieniam go na getContext działa dla mnie
listView LV=getView().findViewById(R.id.listOFsensors);
LV.setAdapter(new ArrayAdapter<String>(getContext(),android.R.layout.simple_list_item_1 ,listSensorType));
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-06-29 12:04:07
Możesz użyć getActivity()
lub getContext
w fragmencie.
Dokumentacja
/**
* 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();
}
I
/**
* Return the {@link Context} this fragment is currently associated with.
*
* @see #requireContext()
*/
@Nullable
public Context getContext() {
return mHost == null ? null : mHost.getContext();
}
Pro tip
Sprawdzaj zawsze if(getActivity!=null)
Ponieważ może być null , gdy fragment nie jest dołączony do aktywności. Czasami wykonywanie długich operacji we fragmencie (jak pobieranie danych z rest api) zajmuje trochę czasu. i jeśli użytkownik przejdzie do innego fragmentu. Wtedy getActivity będzie null. I dostaniesz NPE, jeśli nie poradzisz sobie z tym.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-08-19 04:14:57