如果这是一个非常基本的问题我很抱歉,但如果我从服务器上的文本文件中获取列表项,我该如何设置onListItemClick?我想要做的只是在单击listview上的项目时显示一个toast,但我似乎无法添加onListItemClick来执行此操作。我认为这是因为try / catch?
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Toast;
public class ListView extends ListActivity {
public String[] ListItems = new String[]{};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
URL textUrl;
try {
textUrl = new URL("http://172.30.54.153/databases/result.txt");
BufferedReader bufferReader = new BufferedReader(new InputStreamReader(textUrl.openStream()));
String StringBuffer;
String stringText = "";
stringText.split(",");
while ((StringBuffer = bufferReader.readLine()) != null) {
stringText += StringBuffer;
}
String DbLines = new String(stringText);
ListItems = DbLines.split(",");
setListAdapter(new ArrayAdapter<String>( this,
android.R.layout.simple_list_item_1, ListItems));
bufferReader.close();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void OnListItemClick(ListView Parent,View v, int position, long id) {
// TODO Auto-generated method stub
Toast.makeText(this, "y"+ ListItems[position], Toast.LENGTH_LONG).show();
}
}
答案 0 :(得分:1)
您的问题:
首先,您的私人事件监听器的处理程序位于 private
,因此它不再是继承的方法,您的代码错误 { {1}} 强>:
private
您必须使用扩大覆盖方法的功能范围,意味着公共或受保护。建议,你应该使用@Override标识符来确保你的继承意图。像这样修改您的代码(使用@Override和protected或public):
private void OnListItemClick(ListView Parent,View v, int position, long id)
请参阅SDK指南: ListActivity.onListItemClick()
第二次,您必须使列表视图收听点击事件:
更改班级定义:
@Override
protected void onListItemClick (ListView l, View v, int position, long id)
{
....
}
并在 public class ListView extends ListActivity implements OnItemClickListener
{
...
}
中添加以下代码。这一行将使用指定的侦听器注册当前列表活动(this):
onCreate()
答案 1 :(得分:0)
在你的onCreate中添加:
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(ListView.this, "y"+ ListItems[position], Toast.LENGTH_LONG).show();
}
});
并删除此内容:
private void OnListItemClick(ListView Parent,View v, int position, long id) {
// TODO Auto-generated method stub
Toast.makeText(this, "y"+ ListItems[position], Toast.LENGTH_LONG).show();
}
您可能希望将类重命名为MyListView以避免混淆
答案 2 :(得分:0)
OnListItemClick的Lint
The method OnListItemClick(ListView, View, int, long) from the type ListActivity is never used locally
替换为:
protected void onListItemClick(ListView l, View v, int position, long id)
这是onListItemClick
- on
小写不是OnListItemClick
- On
大写
希望这有帮助!