2014-02-28 53 views
0

我有一個應用程序,我在新聞頂部有一個橫幅,當我想提出其他消息時,我需要打開代碼並更改資源.jpg和鏈接。有一種方法可以在不修改代碼的情況下更改橫幅和鏈接(或至少橫幅)? Idk可能會上傳到網頁或類似的東西。 謝謝我如何「更新」Android中的橫幅?

+0

什麼阻止你在運行時動態更改imageView? – rperryng

回答

1

我的建議是將banner.jpg上傳到您的應用可以訪問並動態加載的服務器。這樣可以防止每次更改橫幅時更新應用程序,並使其更清潔(不會出現過多的Google Play更新)。要做到實際加載圖像,你可以使用此代碼:

ImageView image1 = (ImageView) findViewById(R.id.mybanner); 
new Thread(new Runnable(){//create a new thread so we can do network operations 
    @Override 
    public void run() {//main thread function 
     try {//attempt to do network stuff 
      URL url = new URL("http://your-hosting-site.com/banner.jpg");//create aURL object with the path to your banner 
      HttpURLConnection con = (HttpURLConnection) url.openConnection();//create the connection object from the url 
      con.setReadTimeout(15000); 
      con.setConnectTimeout(15000); 
      con.setRequestMethod("GET"); 
      con.setDoInput(true); 
      con.connect();//connect to the server 
      InputStream is = con.getInputStream();//get the stream so we can read the image 
      Drawable d = Drawable.createFromStream(is, "MyBanner");//create a drawable from the image 
      Bitmap bmp = ((BitmapDrawable) d).getBitmap();//create a bitmap from the drawable 
      final Drawable dS = new BitmapDrawable(Bitmap.createScaledBitmap(bmp, 192, 192, true));//scale it to whatever size you need 
      con.disconnect();//disconnect now that we're done 
      runOnUiThread(new Runnable(){//run UI update code on the main thread 
       @Override 
       public void run() { 
        image1.setImageDrawable(dS);//set the imageview to the banner we downloaded 
       } 
      }); 
     } catch (MalformedURLException e) {//catch url error 
      e.printStackTrace(); 
     } catch (IOException e) {//catch io error when downloading 
      e.printStackTrace(); 
     } 
    } 
}).start();//run the thread 

更改「http://your-hosting-site.com/banner.jpg」(6號線),無論你上傳JPG格式,R.id.mybanner(1號線)到您的ImageView的id ,以及「MyBanner」(第14行),無論你想調用圖像。

您可能希望將橫幅保存到手機中,並且只能在X天/小時後檢查更新以保存數據,但這取決於您。

+0

@ amerite1,謝謝你的回答..我完全是新手,我不明白,因爲每次我上傳橫幅,例如imageshack.com鏈接改變,所以我需要更改代碼的權利?或者我沒有得到dinamically的意思:S –

+0

我會建議獲得一個免費的虛擬主機帳戶,以便您可以上傳圖片並擁有一個關於您的網站展示您的應用。這樣,您可以上傳文件,路徑將保持不變。我個人使用000webhost成功,但你可以看看有什麼。請注意,您不能僅將它們的服務用於文件託管;你將需要一個類似的網站來堅持他們的tos – T3KBAU5