English 中文(简体)
在碎片中利用环境
原标题:Using context in a fragment

我怎么能够把情况一成不变?

I need to use my database whose constructor takes in the context, but getApplicationContext() and FragmentClass.this don t work so what can I do?

数据库构造

public Database(Context ctx)
{
    this.context = ctx;
    DBHelper = new DatabaseHelper(context);
}
最佳回答

You can use getActivity(), which returns the activity associated with a fragment.
The activity is a context (since Activity extends Context).

问题回答

如上文所述,您可优先于<代码>。 沥青/代码

public static class DummySectionFragment extends Fragment{
...
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        DBHelper = new DatabaseHelper(activity);
    }
}

了解我发现的碎片的背景的最容易和最准确的方法是直接从<条码>查询组上查询。 当你打电话onCreateView方法时,你至少可以肯定不会因为getActative():

public class Animal extends Fragment { 
  Context thiscontext;
  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
  {
    thiscontext = container.getContext();

Always use the getActative ( 2. 了解您所附活动情况的方法,但始终牢记: 差异略为不稳定,而getActective Returns no some倍,因此,总是核对isAdded(,在通过getActative()。

正确的方式是使用

requireContext()

以及实例

ContextCompat.getColor(requireContext(), R.color.colorAccent),

此前使用<代码>onAttach(活动)到context载于Fragment

问题

https://developer.android.com/vis/android/app/Fragment.html#onAttach(android.app.Actative)”rel=“noreferer”>onAttach(活动) 已在第23级修改了方法。

Solution

现在,可在<代码>Fragment中查阅,我们可使用>onAttach (Context context)/a>。

<><>>>> Attach (Context context)

  • Called when a fragment is first attached to its context. onCreate(Bundle) will be called after this.

文件

/**
 * 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;
    }

}

NOTE

We can also use getActivity() to get context in Fragments but getActivity() can return null if the your fragment is not currently attached to a parent activity,

必要文字法是最简单的选择

requireContext()

MyDatabase(requireContext())
@Override
public void onAttach(Activity activity) {
    // TODO Auto-generated method stub
    super.onAttach(activity);
    context=activity;
}

您也可从<条码>inflater参数中获取背景,但以<条码>为准。

public static class MyFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
        /* ... */
        Context context = inflater.getContext();
        /* ... */
    }
}

另一种替代办法是:

你们可以利用:

getActivity().getApplicationContext();

可通过<>>>>>:

public Database()
{
    this.context = getActivity();
    DBHelper = new DatabaseHelper(this.context);
}
  • Be careful, to get the Activity associated with the fragment using getActivity(), you can use it but is not recommended it will cause memory leaks.

我认为,必须从<条码>-Attach()方法中获取<条码>。

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    context = activity;
}

You can use the getActivity() method to get context or You can use getContext() method .

View root = inflater.inflate(R.layout.fragment_slideshow, container, false);
Context c = root.getContext();

我希望它能帮助!

。 代之以《刑法》中任何地方的主动性。

如果有的话,请参看该错误。 如果要使用目标与微型亚特兰大目标之间的方法,则会出现这一错误。

由于第23级,有<条码>植被目录(<>>>),但如果您希望支持旧版本,则可以使用<条码>植被(<>代码/代码>,而我仍建议使用<条码>的支持版本,即<条码>>,即

对科特林来说,你可以直接使用<代码>context。 但在某些情况下,你会发现这样的错误。

类型不匹配:假设类型是背景? 但预计情况会有所不同。

val ctx = context ?: return
textViewABC.setTextColor(ContextCompat.getColor(ctx, android.R.color.black))

∗∗∗∗ 仅限使用<条码>而不是<条码>

图书馆使用碎片

android.support.v4.app.Fragment

之后

void onAttach (Context context) {
  this.context = context;
}

这样,你就能够确保环境永远是非核价值。

你们有不同的选择:

  • If your minSDK <= 21, then you can use getActivity(), since this is a Context.
  • If your minSDK is >=23, then you can use getContext().

如果您不需要支持旧版本,则请上getContext()

B. 打破碎片的环境的安全途径

if(isAdded){
requireActivit();//this is your context
}

理想的做法是,你不应使用全球。 碎片有不同的通知,其中一项是主动性的。 在碎片的生命周期活动中,你可以看到活动。

然后,你可以按照你的愿望,将碎块引向活动、环境或应用。

this.getActivity() will give you the handle to the activity this.getContext() will give you a handle to the context this.getActivity().getApplicationContext() will give you the handle to the application context. You should preferably use the application context when passing it on to the db.

简单办法是使用<代码>植被()。 但是,我认为,使用<代号>植被(<>/代码>)方法来这里了解情况,是个无意义的例外。

为此,首先对<代码>isAdded()方法进行核对,以确定其是否添加,然后我们可以使用<代码>植被()来了解活动情况。

请打电话getActative(,或

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;
    }
}

In Kotlin you can use this: requireActivity().applicationContext

我认为你可以使用

public static class MyFragment extends Fragment {
  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

      Context context = getActivity.getContext();

  }
}

在我使用getActative误差时,我需要使用阵列中的阵列,但当我用代替时,它为我工作。

listView LV=getView().findViewById(R.id.listOFsensors);
LV.setAdapter(new ArrayAdapter<String>(getContext(),android.R.layout.simple_list_item_1 ,listSensorType));

在你身上

((Name_of_your_Activity) getActivity()).helper

活动

DbHelper helper = new DbHelper(this);

k子样本中的碎片将有助于某人

textViewStatus.setTextColor(ContextCompat.getColor(context!!, R.color.red))

如果你使用数据具有约束力;

bindingView.textViewStatus.setTextColor(ContextCompat.getColor(context!!, R.color.red))

具有约束力 意见最初载于onCreateView,如此。

private lateinit var bindingView: FragmentBookingHistoryDetailBinding

bindingView = DataBindingUtil.inflate(inflater, R.layout.your_layout_xml, container, false)

androidx.fragment.app.Fragment

@NonNull
public final android.content.Context requireContext()

该碎片目前与背后情况有关。

Since: getActivity and Context can be null, it is good practice to use requireContext() as it can t be null.





相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...