如何在android中的列表项中显示与字符串值对应的图像?

时间:2017-06-06 12:22:12

标签: android listview imageview

我正在开发一个带有列表视图的Android应用程序,我想在每个列表项目中显示两个textview和一个imageview。

textview所需的文本存储在服务器中,并显示在列表视图中。但我还想在drawables文件夹中为每个列表项添加一个相应的图像,存储在移动应用程序中。

我使用链接http://alvideobackend.azurewebsites.net/lesson/Physics访问文本值 并收到课程编号,姓名和子名称。存储在drawables文件夹中的图像与课程编号相对应。例如,课程编号= 1,图像= 1.png

请帮助我在列表项目中显示图像。

SecondActivity.java

package com.example.acer.videoapp;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;


public class SecondActivity extends AppCompatActivity {

    private String TAG = MainActivity.class.getSimpleName();
    private ProgressDialog pDialog;
    private ListView listView1;
    Toolbar toolbar1;
    String subjectName;

    ArrayList<HashMap<String, String>> lessonList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);

        //setting title to toolbar
        toolbar1 = (Toolbar) findViewById(R.id.toolbar1);
        toolbar1.setTitleTextColor(getColor(R.color.white));

        Bundle bundle = getIntent().getExtras();
        if(bundle!=null) {
            toolbar1.setTitle(bundle.getString("description"));
            subjectName=bundle.getString("engdescription");
        }

        lessonList = new ArrayList<>();
        listView1 = (ListView) findViewById(R.id.list);
        new GetLessons().execute();

        listView1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int i, long id) {
                Intent intent = new Intent(SecondActivity.this, ThirdActivity.class);
                HashMap<String, String> lesson = lessonList.get(i);
                intent.putExtra("number", lesson.get("number"));
                intent.putExtra("name", lesson.get("name"));
                startActivity(intent);
            }
        });

        //set back button on toolbar
        toolbar1.setNavigationIcon(R.drawable.back);
        toolbar1.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });



    }

    /* Async task class to get json by making HTTP call */
    private class GetLessons extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Showing progress dialog
            pDialog = new ProgressDialog(SecondActivity.this);
            pDialog.setMessage("Please wait...");
            pDialog.setCancelable(false);
            pDialog.show();

        }

        @Override
        protected Void doInBackground(Void... arg0) {
            HttpHandler sh = new HttpHandler();

            // Making a request to url and getting response
            String url = getResources().getString(R.string.lessons_url, subjectName);
            String jsonStr = sh.makeServiceCall(url);

            Log.e(TAG, "Response from url: " + jsonStr);

            if (jsonStr != null) {
                try {
                    // Getting JSON Array
                    JSONArray lessons = new JSONArray(jsonStr);

                    // looping through All lessons
                    for (int i = 0; i < lessons.length(); i++) {
                        JSONObject c = lessons.getJSONObject(i);

                        String number = c.getString("lessonNo");
                        String name = c.getString("lessonName");
                        String engname = c.getString("lessonEngName");

                        // tmp hash map for single lesson
                        HashMap<String, String> lesson = new HashMap<>();

                        // adding each child node to HashMap key => value
                        lesson.put("number", number);
                        lesson.put("name", name);
                        lesson.put("engname", engname);



                        // adding lesson to lesson list
                        lessonList.add(lesson);
                    }
                } catch (final JSONException e) {
                    Log.e(TAG, "");
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(),"Json parsing error: " + e.getMessage(),Toast.LENGTH_LONG).show();
                        }
                    });

                }
            } else {
                Log.e(TAG, "Please check your Internet Connection");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(),"Couldn't get json from server. Check LogCat for possible errors!",Toast.LENGTH_LONG).show();
                    }
                });

            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            // Dismiss the progress dialog
            if (pDialog.isShowing())
                pDialog.dismiss();
            /**
             * Updating parsed JSON data into ListView
             * */
            ListAdapter adapter = new SimpleAdapter(
                    SecondActivity.this, lessonList,R.layout.list_item1, new String[]{"name","engname",}, new int[]{R.id.lname,R.id.lname1});
            listView1.setAdapter(adapter);

        }


    }

}

list_item1.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <ImageView
        android:id="@+id/img"
        android:layout_gravity="center"
        android:scaleType="fitXY"
        android:editable="true"
        android:layout_width="50dp"
        android:layout_height="50dp" />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:orientation="vertical">

        <TextView
            android:id="@+id/lname"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingBottom="0dip"
            android:paddingTop="20dip"
            android:paddingLeft="10dip"
            android:layout_marginLeft="0dp"
            android:layout_marginRight="5dp"
            android:textSize="17sp"
            android:textColor="@android:color/black"/>

        <TextView
            android:id="@+id/lname1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingBottom="20dip"
            android:paddingTop="0dip"
            android:paddingLeft="10dip"
            android:layout_marginLeft="0dp"
            android:layout_marginRight="5dp"
            android:textSize="13sp"/>

    </LinearLayout>
</LinearLayout>

1 个答案:

答案 0 :(得分:3)

一般方法可以是为列表项构建数据模型,然后在列表中选择新项时,从数据模型中更新图像。

执行此操作的具体方法可能是将您的图像文件名按照它们在列表中显示的顺序加载到数组中,然后,当在列表中选择某个项目时,显示该图像的索引。阵列。