如何在列表视图中获取列表项位置?

时间:2017-02-18 04:28:45

标签: android listview

我的代码将包裹名称从.txt文件填充到ListView中,我想在点击时让每个列表项在Google Play商店中自行打开。如何获取列表项(包名称)?

startActivity(new Intent(
            Intent.ACTION_VIEW,
            Uri.parse("http://play.google.com/store/apps/details?id="
                    + "com.utorrent.client")));

我的列表视图:

    try {
        String filePath = Environment.getExternalStorageDirectory()
                .getAbsolutePath() + "/vers.txt";
        BufferedReader br = new BufferedReader(new InputStreamReader(
                new FileInputStream(filePath), "Cp1252"), 100);

        String line;
        ArrayList<String> lines = new ArrayList<String>();
        while ((line = br.readLine()) != null) {
            lines.add(line);
        }

        br.close();

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, lines);

        listView1.setAdapter(adapter);

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

4 个答案:

答案 0 :(得分:3)

在列表视图上设置onItemClickListener,然后从点击项目的位置获取dataList中的该项目。

 listView.setOnItemClickListener(new OnItemClickListener() {
     @Override
     public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
         startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id="
                + lines.get(position))));
     }
 });

答案 1 :(得分:2)

这是您问题的代码。我使用以下代码实现了相同的功能:

listView.setOnItemClickListener(
            new AdapterView.OnItemClickListener(){
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    String recipes = String.valueOf(parent.getItemAtPosition(position));
                    Toast.makeText(Main22Activity.this, recipes, Toast.LENGTH_LONG).show();
                    Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
                    intent.setData(Uri.parse("https://play.google.com/store/apps/details?id=my packagename "));
                    startActivity(intent);

希望这有帮助!! :)

答案 2 :(得分:0)

尝试以下代码

try{
    InputStream inputreader = getAssets().open("vers.txt");
    BufferedReader buffreader = new BufferedReader(new InputStreamReader(inputreader));

    /*  Enter your code here */
}

答案 3 :(得分:0)

虽然这个问题已经有了答案,但我的答案有正确的方法来获得具体职位的项目

mListView.setOnItemClickListener(new OnItemClickListener() {
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Object obj = mListView.getAdapter().getItem(position);
        //Now this object has everything you need to get

    }
});