android - ListView 的 onListItemClick 不起作用 - Android

标签 android listview onclick

我正在尝试实现 OnListItemClick 但似乎无法让它工作。没有出现错误,没有强制关闭等。下面是我的代码:

package com.odhranlynch.filmCollection;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

import org.apache.http.util.ByteArrayBuffer;

import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class Main extends Activity {
/** Called when the activity is first created. */
private final String databaseFilename = "/films.db"; //filename
private final String url = "www.somesite.com"; //download database from here
ArrayList<FilmRecord> films = new ArrayList<FilmRecord>();

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    DownloadFromUrl(url, databaseFilename);

    ListView listView = (ListView) findViewById(R.id.lstFilms);
    listView.setAdapter(new FilmItemAdapter(this, android.R.layout.simple_list_item_1, films));
}


protected void onListItemClick(ListView l, View v, int position, long id)
{
    //ListItem clicked.
    Log.d("ListView", String.valueOf(l.getSelectedItemPosition()));
}

public void DownloadFromUrl(String DownloadUrl, String fileName) {  
    try {
        File root = android.os.Environment.getExternalStorageDirectory();               

        File dir = new File (root.getAbsolutePath() + "/Android/data/com.odhranlynch.filmcollection");
        if(dir.exists()==false) {
             dir.mkdirs();
        }

        URL url = new URL(DownloadUrl); //you can write here any link
        File file = new File(dir, fileName);

        long startTime = System.currentTimeMillis();
        Log.d("DownloadManager", "download begining");
        Log.d("DownloadManager", "download url:" + url);
        Log.d("DownloadManager", "downloaded file name:" + fileName);

        /* Open a connection to that URL. */
        URLConnection ucon = url.openConnection();

        /*
         * Define InputStreams to read from the URLConnection.
         */
        InputStream is = ucon.getInputStream();
        BufferedInputStream bis = new BufferedInputStream(is);

        /*
         * Read bytes to the Buffer until there is nothing more to read(-1).
         */
        ByteArrayBuffer baf = new ByteArrayBuffer(5000);
        int current = 0;
        while ((current = bis.read()) != -1) {
           baf.append((byte) current);
        }


        /* Convert the Bytes read to a String. */
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(baf.toByteArray());
        fos.flush();
        fos.close();
        Log.d("DownloadManager", "download ready in" + ((System.currentTimeMillis() - startTime) / 1000) + " sec");

        //Download completed, run populateFields method.
        populateFields();

} catch (IOException e) {
    Log.d("DownloadManager", "Error: " + e);
    }
}

public class FilmItemAdapter extends ArrayAdapter<FilmRecord> {
    private ArrayList<FilmRecord> films;

    public FilmItemAdapter(Context context, int textViewResourceId, ArrayList<FilmRecord> films) {
        super(context, textViewResourceId, films);
        this.films = films;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View v = convertView;
        if (v == null) {
            LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            v = vi.inflate(R.layout.listitem, null);
        }

        FilmRecord film = films.get(position);
        if (film != null) {
            TextView filmTitle = (TextView) v.findViewById(R.id.username);
            TextView filmShowingDate = (TextView) v.findViewById(R.id.email);

            if (filmTitle != null) {
                filmTitle.setText(film.filmTitle);
            }

            if(filmShowingDate != null) {
                filmShowingDate.setText("Showing on " + film.filmShowingDate );
            }
        }
        return v;
    }
}

public class FilmRecord {
    public String filmTitle;
    public String filmShowingDate;

    public FilmRecord(String username, String email) {
        this.filmTitle = username;
        this.filmShowingDate = email;
    }
}

public void populateFields() {
    //Populate the views with database content.


    DataBaseHelper myDbHelper = new DataBaseHelper(this);;
    myDbHelper = new DataBaseHelper(this);

    //Load "productDatabase" database (see assets to left).
    {
        try {
            myDbHelper.createDataBase();} 
        catch (IOException ioe) {
            throw new Error("Unable to create database");}

        try {
            myDbHelper.openDataBase();}
        catch(SQLException sqle){
            throw sqle;}
    }

  //---Get all records from database---
    myDbHelper.openDataBase();
    Cursor cursorPosition = myDbHelper.getAllTitles();


    if (cursorPosition.moveToFirst())
    {
    do {
    AddRecordToArray(cursorPosition);
    } while (cursorPosition.moveToNext());
    }
    myDbHelper.close();
    }

    public void AddRecordToArray(Cursor cursorPosition)
    {
        //Add new record to array (which gets data from database using cursorPosition (for current row) and .getstring( for column number).
        FilmRecord film1 = new FilmRecord(cursorPosition.getString(1), cursorPosition.getString(4));
        films.add(film1);
    }
}

如果有人愿意帮助我解决这个问题,我将非常感激:)

最佳答案

您没有将监听器设置到列表中。你需要这样的东西:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    DownloadFromUrl(url, databaseFilename);

    ListView listView = (ListView) findViewById(R.id.lstFilms);
    listView.setAdapter(new FilmItemAdapter(this, android.R.layout.simple_list_item_1, films));
    listView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapter, View view, int pos, long id) {
                Log.d("ListView", String.valueOf(pos));
            }
    });
}

您可能还想向适配器实现添加一些方法,以访问数组的特定元素。

关于android - ListView 的 onListItemClick 不起作用 - Android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9316999/

相关文章:

android - 如何将 viewPager 作为标题添加到 ListView

php - 单击链接销毁 PHP session

jquery - 如何更改点击时的图片来源?

javascript - 从绑定(bind)到主体的选择器中删除某些元素

java - 如何在一行代码中获取和设置字符串数组?

java - 连接 mysql 时 android.app.serviceconnectionleaked

java - 如何在 ListView 中显示??(使用okhttp库)

android - Android Listview 项目中的按钮颜色更改无法正常工作

android - 在 Android Studio 的子模块上运行时移除 jar

Android改变ListView字体