如何在android中的特定TextView字符串上获取图像?

时间:2014-11-15 07:32:41

标签: android xml json imageview

我正在构建一个Android应用程序,其中的数据是从JSON凌空库解析的。

现在我需要的是:在ListView中的特定文本前面应该有一个特定的图像。

例如,如果数据解析字符串是冰淇淋,那么它前面应该有一个冰淇淋图像。

以下是我用于解析数据的代码:

package tabsswipe;

public class FragmentPlay extends Fragment implements OnClickListener {

private Button ib;
private Calendar cal;
private int day;
private int month;
private int year;
private EditText et;



// Movies json url
private static final String url = "url";
private ProgressDialog pDialog;
private List<Movie> movieList = new ArrayList<Movie>();
private ListView listView;
private CustomListAdapter adapter;

String minstring, maxstring,finaldate;
EditText etxt1, etxt2;
String selItem, selItem2, selItem3, selItem4;
int ab, ba;
TextView tv1, tv2, txtsportname;
SeekBarWithTwoThumb swtt;

String firstlist;

public static ArrayList<String> array;
Calendar c = Calendar.getInstance();
int startYear = c.get(Calendar.YEAR);
int startMonth = c.get(Calendar.MONTH);
int startDay = c.get(Calendar.DAY_OF_MONTH);
Spinner spnr;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {



    listView = (ListView) rootView.findViewById(R.id.list1);
    listView.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> adapterView, View view,
                int Position, long offset) {
            // TODO Auto-generated method stub
            Movie item = (Movie) adapter.getItem(Position);
            viewCategorysportdetails();
            // Intent intent = new Intent(rootView.getContext(),
            // SingleArticleAfrica.class);
            // single.title = item.getTitle();
            // single.author = item.getAuthor();
            // single.date = item.getDate();
            // single.featured_img = item.getFeatured_img();
            // single.content = item.getContent();
            // single.permalink = item.getPermalink();
            firstlist = item.getTitle();
            txtsportname.setText(firstlist);
            // Toast.makeText(getActivity(), firstlist,
            // Toast.LENGTH_LONG).show();
            // startActivity(intent);

        }
    });
    adapter = new CustomListAdapter(getActivity(), movieList);
    listView.setAdapter(adapter);

    pDialog = new ProgressDialog(getActivity());
    // Showing progress dialog before making http request
    pDialog.setMessage("Loading...");
    pDialog.show();



    return rootView;
}

    @Override
public void onStart() {
    super.onStart();

    // Creating volley request obj
    JsonArrayRequest movieReq = new JsonArrayRequest(url,
            new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {
                    Log.d(TAG, response.toString());
                    hidePDialog();

                    // Parsing json
                    for (int i = 0; i < response.length(); i++) {
                        try {

                            JSONObject obj = response.getJSONObject(i);
                            Movie movie = new Movie();
                            movie.setTitle(obj.getString("foodname"));
                            // movie.setThumbnailUrl(obj.getString("image"));
                            // movie.setRating(((Number) obj.get("rating"))
                            // .doubleValue());
                            // movie.setYear(obj.getInt("releaseYear"));

                            // adding movie to movies array
                            movieList.add(movie);

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }

                    // notifying list adapter about data changes
                    // so that it renders the list view with updated data
                    adapter.notifyDataSetChanged();
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    VolleyLog.d(TAG, "Error: " + error.getMessage());
                    hidePDialog();

                }
            });

    // Adding request to request queue
    AppController.getInstance().addToRequestQueue(movieReq);
}

@Override
public void onDestroy() {
    super.onDestroy();
    hidePDialog();
}

private void hidePDialog() {
    if (pDialog != null) {
        pDialog.dismiss();
        pDialog = null;
    }
}
}

以下是使用CustomListAdapter添加此解析值的代码:

package info.androidhive.customlistviewvolley.adater;

public class CustomListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<Movie> movieItems;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();

public CustomListAdapter(Activity activity, List<Movie> movieItems) {
    this.activity = activity;
    this.movieItems = movieItems;
}

@Override
public int getCount() {
    return movieItems.size();
}

@Override
public Object getItem(int location) {
    return movieItems.get(location);
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    if (inflater == null)
        inflater = (LayoutInflater) activity
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    if (convertView == null)
        convertView = inflater.inflate(R.layout.list_row, null);

    if (imageLoader == null)
        imageLoader = AppController.getInstance().getImageLoader();
    NetworkImageView thumbNail = (NetworkImageView) convertView
            .findViewById(R.id.thumbnail);
    TextView title = (TextView) convertView.findViewById(R.id.title);
    TextView rating = (TextView) convertView.findViewById(R.id.rating);
    //TextView genre = (TextView) convertView.findViewById(R.id.genre);
    TextView year = (TextView) convertView.findViewById(R.id.releaseYear);

    // getting movie data for the row
    Movie m = movieItems.get(position);

    // thumbnail image
    thumbNail.setImageUrl(m.getThumbnailUrl(), imageLoader);

    // title
    title.setText(m.getTitle());

    // rating
    rating.setText((m.getRating()));



    // release year
    year.setText(String.valueOf(m.getYear()));

    return convertView;
}

}

这是XML代码:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFFFFF">

<ListView
    android:id="@+id/list1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:divider="@color/list_divider"
    android:dividerHeight="1dp"
    android:listSelector="@drawable/list_row_selector" /> 


</RelativeLayout>

这是ListAdapter XML:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@drawable/list_row_selector"
android:padding="8dp" >

<!-- Thumbnail Image -->
<com.android.volley.toolbox.NetworkImageView
    android:id="@+id/thumbnail"
    android:layout_width="80dp"
    android:layout_height="80dp"
    android:layout_alignParentLeft="true"
    android:layout_marginRight="8dp" />

<!-- Movie Title -->
<TextView
    android:id="@+id/title"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignTop="@+id/thumbnail"
    android:layout_toRightOf="@+id/thumbnail"
    android:textSize="@dimen/title"
    android:textStyle="bold" />

<!-- Rating -->
<TextView
    android:id="@+id/rating"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_below="@id/title"
    android:layout_marginTop="1dip"
    android:layout_toRightOf="@+id/thumbnail"
    android:textSize="@dimen/rating" />



<!-- Release Year -->
<TextView
    android:id="@+id/releaseYear"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentRight="true"
    android:textColor="@color/year"
    android:textSize="@dimen/year" />

2 个答案:

答案 0 :(得分:1)

static List<String> foodnames = Arrays.asList((getResources().getStringArray(R.array.food_names)));

int key = foodnames.indexOf(getString(m.getFoodName())); 
String[] food_name_drawables = context.getResources().getStringArray(R.array.food_name_drawables);

ImageView foodname = (ImageView) convertView.findViewById(R.id.image_foodname);
background.setBackgroundDrawable(context.getResources().getDrawable(food_name_drawables[key]);

我认为它应该有用......

答案 1 :(得分:0)

我希望我理解你的需要,但我不确定。您是否需要将列表元素视图的背景设置为表示电影类型的图像?那是对的吗?如果是这样:

  • 如果从不属于您的服务器获取信息,请记下网站使用的所有类型,将它们放在一个数组中,并在适配器中根据哪种类型list元素的影片,你改变从drawable数组中获取它的背景。假设只有3种类型:
    在xml中:

    <string-array name="movie_genres">
            <item>Dramatic</item>
            <item>Comedy</item>
            <item>Action</item>
    </string-array>
    
    <string-array name"movie_genres_drawables">
        <item>@drawable/dramatic_image</item>
        <item>@drawable/comedy_image</item>
        <item>@drawable/action_image</item>
    </string-array>
    

    然后在适配器中:

    static List<String> genres;
    ...
    ...
    
    if (genres == null) {
    genres = Arrays.asList((getResources().getStringArray(R.array.movie_genres)));
    }
    
    int key = genres.indexOf(getString(m.getGenre())); //Of course you should create this getter
    
    String[] movie_genres_drawables = context.getResources().getStringArray(R.array.movie_genres_drawables);
    
    ImageView background = (ImageView) convertView.findViewById(R.id.background);
    background.setBackgroundDrawable(context.getResources().getDrawable(movie_genres_drawables[key]);
    

  • 如果您拥有带有电影档案的网站,那么您可以直接从服务器获取图像并将其放在列表中......
  • 如果我完全误解了你的问题,我很抱歉不考虑我的回答。 ; - )