How to get the current context?

2020-05-17 04:42发布

I want to use it in my array adapter. When I put this in a sub-activity to create an adapter it does not work.

标签: android
5条回答
女痞
2楼-- · 2020-05-17 04:42

You can get context a few ways:

By the Activity, using Your_Activity_Name.this

By the application, using getApplicationContext()

By the View, using Your_View.getContext()

The only one I would not recommend is using getBaseContext(). If you need something universal, have a public static variable in your main activity and assign the application context to it when your app starts. This way you can always call Your_Activity.your_context_variable

查看更多
Deceive 欺骗
3楼-- · 2020-05-17 04:46

Here we take variable context :

private Context acontext;

Make the constructor of adapter take another input like:

 public Adapter_order_cancel(Context context,String[] myDataset, String[] job_id, String[] category, String[] name, String[] address) {
        mDataset = myDataset;
        _job_id = job_id;
        _category = category;
        _name = name;
        acontext = context;
    }

This is a click listener in which we used context:

v.setOnClickListener(new View.OnClickListener() {

                @Override public void onClick(View v) {
                    Toast.makeText(itemView.getContext(), "Position: " + Integer.toString(getAdapterPosition()), Toast.LENGTH_LONG).show();
                    acontext.startActivity(new Intent(acontext, OrderDetailPage.class));

                }
            });
查看更多
家丑人穷心不美
4楼-- · 2020-05-17 04:49

getApplicationContext() can get the context value

查看更多
不美不萌又怎样
5楼-- · 2020-05-17 05:05
趁早两清
6楼-- · 2020-05-17 05:09

Besides the correct previous answers, you may want to think about refactoring your code if you've come to the point where you need to access "your" context from a sub activity. When you create a sub activity (ie: startActivityForResult) you are truly waiting for a result, not for an action in the caller activity. Then, when the sub activity has finished (and you have the result of its calculations), you can access your context in a proper way. It just doesn't seem fine that the subactivity is aware of its creator, not to mention interact with it.

查看更多
登录 后发表回答