设置备用行颜色列表视图

时间:2014-09-04 03:02:24

标签: android listview

我知道有很多这方面的教程,但所有这些似乎都不适合我正在使用的当前代码结构。您能否根据我的代码结构指导我如何在列表视图中使用备用颜色行?

MainActivity:

public class MainActivity extends Activity {

private TextView cityText;
private TextView condDescr;

private ImageView imgView;

private ListView mainListView;
private ArrayAdapter<String> listAdapter;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    String city = "";

    mainListView = (ListView) findViewById(R.id.mainListView);

    cityText = (TextView) findViewById(R.id.cityText);
    condDescr = (TextView) findViewById(R.id.condDescr);
    imgView = (ImageView) findViewById(R.id.condIcon);

    ArrayList<String> weatherData = new ArrayList<String>();

    WeatherAdapter listAdapter = new WeatherAdapter (this, weatherData);

    JSONWeatherTask task = new JSONWeatherTask();
    task.execute(new String[] { city });
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

private class JSONWeatherTask extends AsyncTask<String, Void, Weather> {

    @Override
    protected Weather doInBackground(String... params) {
        Weather weather = new Weather();
        String data = ((new WeatherHttpClient()).getWeatherData(params[0]));

        try {
            weather = JSONWeatherParser.getWeather(data);

            // Retrieve the icon
            weather.iconData = ((new WeatherHttpClient())
                    .getImage(weather.currentCondition.getIcon()));

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

    }

    @Override
    protected void onPostExecute(Weather weather) {
        super.onPostExecute(weather);

        if (weather.iconData != null && weather.iconData.length > 0) {
            Bitmap img = BitmapFactory.decodeByteArray(weather.iconData, 0,
                    weather.iconData.length);
            imgView.setImageBitmap(img);
        }

        cityText.setText(weather.location.getCity() + ", "
                + weather.location.getCountry());
        condDescr.setText("Weather: " + weather.currentCondition.getCondition() + " ("
                + weather.currentCondition.getDescr() + ")");
        listAdapter.add("Temperature: "
                + Math.round((weather.temperature.getTemp() - 273.15))
                + "°C");
        listAdapter.add("Humidity: " + weather.currentCondition.getHumidity() + "%");
        listAdapter.add("Pressure: " + weather.currentCondition.getPressure() + " hPa");
        listAdapter.add("Wind speed: " + weather.wind.getSpeed() + " mps");
        listAdapter.add("Wind degree: " + weather.wind.getDeg() + "°");

        // Set the ArrayAdapter as the ListView's adapter.
        mainListView.setAdapter(listAdapter);
    }

}
}

自定义适配器:

public class WeatherAdapter extends ArrayAdapter<String> {
private final Activity context;
private static String[] weatherData;

static class ViewHolder {
    public TextView text;
    public ImageView image;
}

public WeatherAdapter(Activity context, String[] weatherData) {
    super(context, R.layout.list, weatherData);
    this.context = context;
    this.weatherData = weatherData;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View rowView = convertView;
    // reuse views
    if (rowView == null) {
        LayoutInflater inflater = context.getLayoutInflater();
        rowView = inflater.inflate(R.layout.list, null);
        // configure view holder
        ViewHolder viewHolder = new ViewHolder();
        /*
         * viewHolder.text = (TextView)
         * rowView.findViewById(R.id.TextView01); viewHolder.image =
         * (ImageView) rowView .findViewById(R.id.ImageView01);
         */
        rowView.setTag(viewHolder);
    }

    ViewHolder holder = (ViewHolder) rowView.getTag();
    String s = weatherData[position];
    holder.text.setText(s);
    if (s.startsWith("Temperature") || s.startsWith("Pressure")
            || s.startsWith("Wind Degree")) {
        rowView.setBackgroundColor(Color.BLUE);
    } else {
        rowView.setBackgroundColor(Color.CYAN);
    }

    return rowView;
}
}

如何将自定义适配器应用于我的主要活动?目前,只执行我的主要活动,我的列表视图是一种颜色。

3 个答案:

答案 0 :(得分:0)

您的构造函数格式错误,您需要将构造函数的参数中的字符串数组提交给超级构造函数:

public WeatherAdapter(Activity context, ArrayList<String> names) {
super(context, R.layout.list, names);
this.context = context;
this.weatherData = names;

}

修改后的课程

public class WeatherAdapter extends ArrayAdapter<String> {
private final Activity context;
private static ArrayList<String> weatherData;

static class ViewHolder {
    public TextView text;
    public ImageView image;
}

public WeatherAdapter(Activity context, ArrayList<String> names) {
    super(context, R.layout.list, names);
    this.context = context;
    this.weatherData = names;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View rowView = convertView;
    // reuse views
    if (rowView == null) {
        LayoutInflater inflater = context.getLayoutInflater();
        rowView = inflater.inflate(R.layout.list, null);
        // configure view holder
        ViewHolder viewHolder = new ViewHolder();
        /*
         * viewHolder.text = (TextView)
         * rowView.findViewById(R.id.TextView01); viewHolder.image =
         * (ImageView) rowView .findViewById(R.id.ImageView01);
         */
        rowView.setTag(viewHolder);
    }

    ViewHolder holder = (ViewHolder) rowView.getTag();
    String s = weatherData.get(position);
    holder.text.setText(s);
    if (s.startsWith("Temperature") || s.startsWith("Pressure")
            || s.startsWith("Wind Degree")) {
        rowView.setBackgroundColor(Color.BLUE);
    } else {
        rowView.setBackgroundColor(Color.CYAN);
    }

    return rowView;
}
}

现在使用它是:

listAdapter = new WeatherAdapter(this, weatherData);

答案 1 :(得分:0)

listAdapter = new WeatherAdapter (this, R.layout.list, weatherData);似乎错了,你应该尝试使用它:

listAdapter = new WeatherAdapter (context, weatherData);

答案 2 :(得分:0)

我设法解决了它。以下是我更新的代码。

MainActivity:

public class MainActivity extends Activity {

private TextView cityText;
private TextView condDescr;

private ImageView imgView;

private ListView mainListView;
private ArrayAdapter<String> listAdapter;
WeatherAdapter wa;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    String city = "";

    mainListView = (ListView) findViewById(R.id.mainListView);

    cityText = (TextView) findViewById(R.id.cityText);
    condDescr = (TextView) findViewById(R.id.condDescr);
    imgView = (ImageView) findViewById(R.id.condIcon);

    // Create and populate a List of variable names.
    String[] weather = new String[] {};
    ArrayList<String> weatherData = new ArrayList<String>();
    weatherData.addAll(Arrays.asList(weather));


    listAdapter = new WeatherAdapter(this, weatherData);


    JSONWeatherTask task = new JSONWeatherTask();
    task.execute(new String[] { city });
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

private class JSONWeatherTask extends AsyncTask<String, Void, Weather> {

    @Override
    protected Weather doInBackground(String... params) {
        Weather weather = new Weather();
        String data = ((new WeatherHttpClient()).getWeatherData(params[0]));

        try {
            weather = JSONWeatherParser.getWeather(data);

            // Retrieve the icon
            weather.iconData = ((new WeatherHttpClient())
                    .getImage(weather.currentCondition.getIcon()));

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

    }

    @Override
    protected void onPostExecute(Weather weather) {
        super.onPostExecute(weather);

        if (weather.iconData != null && weather.iconData.length > 0) {
            Bitmap img = BitmapFactory.decodeByteArray(weather.iconData, 0,
                    weather.iconData.length);
            imgView.setImageBitmap(img);
        }

        cityText.setText(weather.location.getCity() + ", "
                + weather.location.getCountry());
        condDescr.setText("Weather: " + weather.currentCondition.getCondition() + " ("
                + weather.currentCondition.getDescr() + ")");
        listAdapter.add("Temperature: "+ "\t\t\t\t"
                + Math.round((weather.temperature.getTemp() - 273.15))
                + "°C");
        listAdapter.add("Humidity: " + "\t\t\t\t\t\t" + weather.currentCondition.getHumidity() + "%");
        listAdapter.add("Air pressure: " + "\t\t\t\t" + weather.currentCondition.getPressure() + " hPa");
        listAdapter.add("Air condition: " + "\t\t\t\t");


        // Set the ArrayAdapter as the ListView's adapter.
        mainListView.setAdapter(listAdapter);
    }

}

WeatherAdapter:

public class WeatherAdapter extends ArrayAdapter<String> {
private final Activity context;
private ArrayList<String> weatherData;

static class ViewHolder {
    public TextView text;
    public ImageView image;
}

public WeatherAdapter(Activity context, ArrayList<String> weatherData) {
    super(context, R.layout.list, weatherData);
    this.context = context;
    this.weatherData = weatherData;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View rowView = convertView;
    // reuse views
    if (rowView == null) {
        LayoutInflater inflater = context.getLayoutInflater();
        rowView = inflater.inflate(R.layout.list, null);
        // configure view holder
        ViewHolder viewHolder = new ViewHolder();
        viewHolder.text = (TextView) rowView.findViewById(R.id.rowTextView);
        /*
         * viewHolder.text = (TextView)
         * rowView.findViewById(R.id.TextView01); */
        viewHolder.image = (ImageView) rowView .findViewById(R.id.icon);      

        rowView.setTag(viewHolder);
    }

    ViewHolder holder = (ViewHolder) rowView.getTag();
    ArrayList<String> s = new ArrayList<String>(weatherData);
    String []sa = new String [s.size()];
    sa = s.toArray(sa);

    holder.text.setText(sa[position]);

    if (sa[position].startsWith("Air pressure")) {
        rowView.setBackgroundResource(R.color.skyblue) ;

    }           

    return rowView;
}
}