我有一个应用程序,我在顶部有一个横幅用新闻,当我想要打开其他新闻时我需要打开代码并更改资源.jpg和链接。有一种方法可以在不修改代码的情况下更改横幅和链接(或至少是横幅)吗? Idk可能会将其上传到网页或类似的内容。 感谢
答案 0 :(得分: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天/小时后检查是否有更新以保存数据,但这取决于您。