如何在列表视图中找到项目的位置

时间:2018-07-23 10:41:48

标签: android

我创建了一个自定义listView,在其中放置了一些文本和图像,但是当我单击列表视图时,它们没有响应。我创建了一个自定义Listview。 如果有人知道,请告诉我。 我的代码在这里

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    final List<pdf> pdfList;

    //the listview
    final ListView listView;

        //initializing objects
      pdfList = new ArrayList<>();
        listView = (ListView) findViewById(R.id.list);

        //adding some values to our list
      pdfList.add(new pdf("Book1", "First Year"));
     pdfList.add(new pdf( "Book2", "First Year"));
        //creating the adapter
        ListAdptot adapter = new ListAdptot(this, R.layout.customlistview, pdfList);

        //attaching adapter to the listview
        listView.setAdapter(adapter);

    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                    @Override
                                    public void onItemClick (AdapterView < ? > adapter, View view, int position, long arg){

                                       if(position==0)
                                       {
                                           Toast.makeText(MainActivity.this, "Position 0", Toast.LENGTH_SHORT).show();
                                       }

                                      else if(position==1)
                                        {
                                            Toast.makeText(MainActivity.this, "Position 1", Toast.LENGTH_SHORT).show();
                                        }
                                    }
                                }
    );
    }
}

2 个答案:

答案 0 :(得分:2)

按如下所示获取列表项位置

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                @Override
                                public void onItemClick (AdapterView < ? > adapter, View view, int position, long arg){

                                  String value = listView.getItemAtPosition(position).toString();
                                }
                            }
);

答案 1 :(得分:0)

如果列表项中有任何可单击的视图,则它将消耗ListView项目单击的click事件。

在您的android:focusable="false"Button上设置ImageButton

引用SO answer