java - Android - 无法向上滚动

标签 java android scroll adapter

首先,我三周前第一次接触到 Java,所以如果这段代码很糟糕,请耐心等待。这是学校的一项作业,我要在原型(prototype)应用程序的基础上构建并为其提供 UI,因此适配器基本上就是我对此所做的全部工作。

我的问题是,一旦我触摸滚动条,我就会被扔到列表的底部,并且无法向上滚动而不被推回。

/**
 * VaxjoWeather.java
 * Created: May 9, 2010
 * Jonas Lundberg, LnU
 */

package dv106.weather;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import android.app.ListActivity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

/**
 * This is a first prototype for a weather app. It is currently 
 * only downloading weather data for Växjo. 
 * 
 * This activity downloads weather data and constructs a WeatherReport,
 * a data structure containing weather data for a number of periods ahead.
 * 
 * The WeatherHandler is a SAX parser for the weather reports 
 * (forecast.xml) produced by www.yr.no. The handler constructs
 * a WeatherReport containing meta data for a given location
 * (e.g. city, country, last updated, next update) and a sequence 
 * of WeatherForecasts.
 * Each WeatherForecast represents a forecast (weather, rain, wind, etc)
 * for a given time period.
 * 
 * The next task is to construct a list based GUI where each row 
 * displays the weather data for a single period.
 * 
 *  
 * @author jlnmsi
 *
 */

public class VaxjoWeather extends ListActivity {
    //private InputStream input;
    private WeatherReport report = null;

    //private ArrayList<WeatherForecast> forecastList = new ArrayList<WeatherForecast>();

    private WeatherAdapter adapter;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        adapter = new WeatherAdapter(this);
        setListAdapter(adapter);

        //getListView().setTranscriptMode(ListView.TRANSCRIPT_MODE_DISABLED);

        try {
            URL url = new URL("http://www.yr.no/sted/Sverige/Kronoberg/V%E4xj%F6/forecast.xml");
            AsyncTask task = new WeatherRetriever().execute(url);
        } catch (IOException ioe ) {
            ioe.printStackTrace();
        }

        //adapter.notifyDataSetChanged();
    }

    private void PrintReportToConsole() {
        if (this.report != null) {
            /* Print location meta data */ 
            //System.out.println(report);

            /* Print forecasts */
            int count = 0;
            for (WeatherForecast forecast : report) {
                count++;                
                adapter.add(forecast);
            }
        }
        else {
            System.out.println("Weather report has not been loaded.");
        }
        //adapter.notifyDataSetChanged();
    }

    private class WeatherRetriever extends AsyncTask<URL, Void, WeatherReport> {
        protected WeatherReport doInBackground(URL... urls) {
            try {
                return WeatherHandler.getWeatherReport(urls[0]);
            } catch (Exception e) {
                throw new RuntimeException(e);
            } 
        }

        protected void onProgressUpdate(Void... progress) {

        }

        protected void onPostExecute(WeatherReport result) {
            report = result;
            PrintReportToConsole();
        }
    }

    // custom ArrayAdpater to show, weather icon, temperature, and precipation.
    class WeatherAdapter extends ArrayAdapter<WeatherForecast> {

        public WeatherAdapter(Context context) {
            super(context,R.layout.forecast);
        }

        @Override   // Called when updating the ListView
        public View getView(int position, View convertView, ViewGroup parent) {
            View row;
            if (convertView == null) {  // Create new row view object           
                LayoutInflater inflater = getLayoutInflater();
                row = inflater.inflate(R.layout.forecast,parent,false);
            }
            else    // reuse old row view to save time/battery
                row = convertView;

            // TextView for Temperature
            TextView temperature = (TextView)row.findViewById(R.id.temperature);
            temperature.setText(Integer.toString(this.getItem(position).getTemp())+" °C");

            // TextView for out Precipation.
            TextView precipation = (TextView)row.findViewById(R.id.rain);
            precipation.setText(String.valueOf(this.getItem(position).getRain())+" mm");

            // Image Icon for forecast.
            ImageView icon = (ImageView)row.findViewById(R.id.icon);
            String iconPath = "ic_";            

            if (this.getItem(position).getWeatherCode() <= 9){
                iconPath = iconPath+"0"+(Integer.toString(this.getItem(position).getWeatherCode()));
            }
            else {
                iconPath = iconPath+(Integer.toString(this.getItem(position).getWeatherCode()));
            }

            int resId = getResources().getIdentifier(iconPath, "drawable", getPackageName());

            // If the resource ID is invalid, as in the image not existing, we'll add the postfix for periods.
            if (resId == 0){

                // Set the icon image source dependent on period code given.
                if(this.getItem(position).getPeriodCode() == 3){
                    iconPath = iconPath +"n";
                }

                else if (this.getItem(position).getPeriodCode() == 2){

                    iconPath = iconPath +"d";
                }
                else {
                    iconPath = iconPath +"m";
                }

                resId = getResources().getIdentifier(iconPath, "drawable", getPackageName());
                icon.setImageResource(resId);
            }
            // Or if everything checked out, we'll just run with the resource ID and find our Icon.
            else {
                icon.setImageResource(resId);
            }

            return row;
        }
    }

}

我尝试应用另一个标准数组适配器,实际上得到了相同的不需要的滚动结果,所以我不知道我遇到问题的是哪个部分。

最佳答案

实现方法是: 1:将ListView放在main.xml中 2:在您的 Activity 中像这样创建 ListView 对象 -> private ListView listView;在 onCreate 中将其连接到 main.xml,如下所示,listView = (ListView) R.id.listView1;//不管它叫什么

3:接下来创建一个ArrayList:-> private ArrayList arrayWeather = new ArrayList();

4:用天气数据填充数组列表,最后创建您创建的类的对象,并使其使用您的数组列表来显示数据。

示例: 公共(public)类 ListUser 扩展 BaseAdapter{

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return arraylistData.size(); // the arraylist u created
    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return arraylistData.get(position);
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return arraylistData.size();
    }

    @Override
    public View getView(final int position, View v, ViewGroup parent) {
        if(v == null){
            LayoutInflater lf = (LayoutInflater) BuyPets.this.getSystemService( Context.LAYOUT_INFLATER_SERVICE);
            v = lf.inflate(R.layout.forecast, null);
        }


        // setup here, done


        return v;
    }

}

关于java - Android - 无法向上滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26151463/

相关文章:

java - 使用 BufferReader 和 BufferedWriter 写入文件时,文件创建为空

javascript - 使用 jQuery 更改依赖于滚动位置的类时遇到问题

ios - 可滚动 TextView : shows bottom of text as first

android BottomSheet 没有扩展到最大高度

jquery - WOW JS 不适用于一页滚动

java - 如何使用java从给定字符串中获取精确匹配关键字?

java - 安卓接听来电

java - 使用 Spring Boot 从不存在的地址发送邮件失败 : Requires password?

java - DocumentBuilderFactory#newInstance() 如何成为抽象工厂模式的一个例子?

android - 使用 ImageLoader 显示带有外部图像链接的通知