2017-02-18 110 views
0

我的代碼將包名從.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(); 
    } 
} 
+1

也許你應該在你的'ListView' – Karakuri

回答

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)))); 
    } 
}); 
+0

@joey從你的代碼中,行是你存儲包名的ArrayList。所以試着把ArrayList lines = new ArrayList <>();作爲一個全球變量。 –

+0

沒有必要讓這個全局變量適配器可以用於這個目的 –

+0

這個答案可能會在瀏覽器中打開您的應用程序鏈接。要直接打開Goog​​le Play商店,請使用'Uri.parse(「market:// details?id =」+ lines.get(position))'代替整個網址。 –

0

試試下面的代碼

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

    /* Enter your code here */ 
} 
+0

使用'OnItemClickListener'特定位置的項目並沒有解答問題 – Redman

1

這裏是你的問題代碼。我使用此代碼實現了相同的功能:

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); 

希望這有助於! :)

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 

    } 
}); 
相關問題