dswg47377
2013-04-11 10:03 阅读 83

Android - 在ListView中显示背景图像

I am a newbie in android. I have started android for only 2 days. I have tried googling on what I needed to do to make the background image in a listview, but all the codes were all too complicated that I couldn't understand, so please don't vote me down.

My list view is supposed to display a background image from the server. I have accomplished connecting my app to the server. I am able to display the url of the images.

Here is my php code:

AndroidHome.php

<?php

$con = mysql_connect("localhost", "load2unet_root", "hzXC3rUm");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}

mysql_select_db("load2unet_db", $con);
$result = mysql_query("SELECT Photo FROM Home ORDER BY HomeID DESC");

while($row = mysql_fetch_assoc($result))
{
    $output[] = $row;
}
print(json_encode($output));
mysql_close($con);

?>

Here is my .java

HomeActivity.java

//@SuppressLint("NewApi")

public class HomeActivity extends ListActivity{


//String to display in ListView
String [] hello = {
        "Red",
        "Blue",
        "White",
        "Black",
        "Orange",
        "Pink"
};

ArrayList<String> arrayDataFromServer = new ArrayList<String>();
String array;
String [] thisarray;
@SuppressLint("NewApi")
@Override  
public void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    //setContentView(R.layout.activity_home); 

    StrictMode.enableDefaults();
    String result ="";
    InputStream isr = null;
    try{
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new     HttpPost("http://www.mysite.com/android/AndroidHome.php");
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        isr = entity.getContent();

    }
    catch (Exception e)
    {
        Log.e("log_tag", "Error in http connection" +e.toString());
        //resultView.setText("Couldn't connect to database");
    }

    try {
        BufferedReader reader = new BufferedReader(new    InputStreamReader(isr, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null)
        {
            sb.append(line + "
");
        }

        result = sb.toString();
        Log.e("log_tag", "BufferedReader:" +result);
    }

    catch(Exception e)
    {
        Log.e("log_tag, Error converting result"+e.toString(), result);
    }

    try {
        String s = "";
        JSONArray jArray = new JSONArray(result);

        for (int i = 0; i< jArray.length(); i++)
        {
            JSONObject json = jArray.getJSONObject(i);
            array=json.getString("Photo");
            arrayDataFromServer.add(array);
            Log.e("log_tag", "Array: " +array);
            Log.e("log_tag", "arrayDataFromServer: " +arrayDataFromServer);

        }

    }
    catch (Exception e)
    {
        Log.e("log_tag", "Error Parsing Data"+e.toString());
    }
    setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, arrayDataFromServer));

}
public void onListItemClick(
        ListView parent, View v, int position, long id)
{
    //Toast.makeText(this, "You have selected" + colors[position], Toast.LENGTH_LONG).show();
}

}

activity_home.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">
    <!-- Main ListView
         Always give id value as list(@android:id/list)
    -->


    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </ListView>

</LinearLayout>

I am thinking that at the setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, arrayDataFromServer)); I can use some different code to display it in a background image?

Any help would be very much appreciated. Thanks in Advance!

EDIT

String urlString = URLEncoder.encode(array);
            URL url = new URL(urlString);
            Bitmap bm = BitmapFactory.decodeStream(url.openConnection().getInputStream());
            Drawable dr = new BitmapDrawable(bm); // that's the bitmap you downloaded from your server
            getListView.setBackground(dr);
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

1条回答 默认 最新

  • 已采纳
    donglv9116 donglv9116 2013-04-11 10:09

    to answer your question:

     // you can call this from inside the ListActivity
     Drawable dr = new BitmapDrawable(bitmap); // that's the bitmap you downloaded from your server
     getListView().setBackground(dr);
    

    to give extra advice for a noob:

    DO NOT use StrictMode.enableDefaults(); with that you're masking out a very good protection against bad code. Learn how to do it properly. AsyncTask is a very popular and very easy to use threading platform and you should use it. And if you feel confident and adventurous use Loaders which are a bit more complex but far more powerful!

    点赞 评论 复制链接分享

相关推荐