2012-10-31 48 views
1

我想在檢查互聯網的狀態後更改imageview圖像。 基本的,我想檢查互聯網是否工作,如果它我想要顯示某個圖像。檢查互聯網狀態後更改ImageView圖像

這裏我的代碼:

public void onClick(View v) { 

    // get Internet status 
    isInternetPresent = cd.isConnectingToInternet(); 

    // check for Internet status 
    if (isInternetPresent) { 
     // Internet Connection is Present 
     // make HTTP requests 
     showAlertDialog(AndroidDetectInternetConnectionActivity.this, "Internet Connection", "You have internet connection", true); 
    } else { 
     // Internet connection is not present 
     // Ask user to connect to Internet 
     showAlertDialog(AndroidDetectInternetConnectionActivity.this, "No Internet Connection", "You don't have internet connection.", false); 
    } 
} 

回答

0

我是假設你有在Android的檢查互聯網的知識。

在OnCreate中使用

這樣的:

imagev = (ImageView)findviewbyid(R.id.imageview); 

onbutton點擊:

public void onClick(View v) { 

       // get Internet status 
       isInternetPresent = cd.isConnectingToInternet(); 

       // check for Internet status 
       if (isInternetPresent) { 
        // Internet Connection is Present 
        // make HTTP requests 
        showAlertDialog(AndroidDetectInternetConnectionActivity.this, "Internet Connection", 
          "You have internet connection", true); 
           imagev.setImageDrawable(getResources().getDrawable(R.drawable.withinternet)); 

       } else { 
        // Internet connection is not present 
        // Ask user to connect to Internet 
        showAlertDialog(AndroidDetectInternetConnectionActivity.this, "No Internet Connection", 
          "You don't have internet connection.", false); 
       imagev.setImageDrawable(getResources().getDrawable(R.drawable.nointernet)); 
       } 
+0

好的,非常感謝。這真的有助於 – MoschDev

+0

當放在創建代碼它給我一個錯誤的任務 – MoschDev

+0

你得到什麼類型的錯誤?強迫關閉?還是其他什麼? –

0

以下方法用於檢查網絡是否可用

public static boolean isOnline(Activity context) { 
    ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE); 
    NetworkInfo netInfo = cm.getActiveNetworkInfo(); 
    if (netInfo != null && netInfo.isConnected()) { 
     return true; 
    } 
    return false; 
} 

在清單文件中設置下面的權限

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> 

然後檢查類似下面

if(isOnline()) 
    img.setImageResource(); 
else 
    img.setImageResource(); 
0

試試這個改變的ImageView圖像。

your_ImageView.setBackgroundResource(R.drawable.your_image_name);