我正在使用Glide
函数从服务器响应中加载图像。下面的代码在onViewCreated
函数中正常工作,但我想建立一个Handler
来验证互联网连接,并且我将Runnable
声明为全局变量。在Runnable
内部我不能使用getActivity
作为上下文/容器。我该怎么用?
以下是onViewCreated()
内的代码:
try {
Glide.with(this.getActivity()).load(jsonObject.getString("dispensary_thumbmail")).into(image);
} catch (JSONException e) {
e.printStackTrace();
}
这是Runnable
:
Runnable runnable = new Runnable() {
@Override
public void run() {
if(!isNetworkConnected())
{
handler.postDelayed(runnable , time);
}
else
{
try {
jsonObject = new JSONObject(MainActivity.dispensaries);
jsonArray = jsonObject.optJSONArray("dispensaries");
Log.e(TAG, "jsonArray = " + jsonArray);
jsonObject = null;
} catch (JSONException e) {
e.printStackTrace();
}
for (int i = 0; i < jsonArray.length(); i++) {
try {
JSONObject object = jsonArray.getJSONObject(i);
if(MainActivity.ID.equals(object.get("dispensary_id")))
{
jsonObject = object;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
try {
Glide.with(this.).load(jsonObject.getString("dispensary_thumbmail")).into(image);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
};
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
答案 0 :(得分:1)
试试这个,基本上,你需要 runOnUiThread 的活动类
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
try {
Glide.with(getActivity()).load(jsonObject.getString("dispensary_thumbmail")).into(image);
} catch (JSONException e) {
e.printStackTrace();
}
}
});