ListView创建了一个超出需要的项目

时间:2015-10-30 18:38:14

标签: android listview

我有一个position填充在我的MainActivity中,但是当我想找到所选项目时,所有项目看起来都具有相同的位置。

(.processes[] | select(.version == "3.0.7")).version = "3.0.6"

这会产生如下列表:

ListView

我有一个按钮,单击它时会运行此方法:

protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_select_teams);

        ListView mainListView;

        // Find the ListView in the UI.
        mainListView = (ListView) findViewById( R.id.listView );

        String values = "Team A vs Team B=Team C vs Team D";

        //Matches are send in one long string, and are separated by the = sign.
        //This splits the string up and puts it into an array.
        String[] array = values.split("=", -1);

        ArrayList<String> arraylist = new ArrayList<String>();
        arraylist.addAll( Arrays.asList(array) );

        ArrayAdapter listAdapter;

        // Create ArrayAdapter using the planet list.
        listAdapter = new ArrayAdapter<String>(this, R.layout.list_view_style, arraylist);


        // Set the ArrayAdapter as the ListView's adapter.
        mainListView.setAdapter(listAdapter);

}

但是,无论何时单击按钮,无论选择列表视图中的哪个项目,toast都会显示相同的值。这是为什么?

1 个答案:

答案 0 :(得分:0)

您应该使用适配器getView方法,如下所示:

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    LayoutInflater inflater = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    if (convertView == null) {
        convertView = inflater.inflate(R.layout.some_layout, parent,
                false);
        convertView.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {

           //here get what you need by the position

        }
    });
    }


 }