【问题标题】:ListView creates one more item than neededListView 创建的项目比需要的多一项
【发布时间】:2015-10-30 18:38:13
【问题描述】:

我的 MainActivity 中填充了一个 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);

}

这样的列表如下:

Team A vs Team B    [checkbox]
Team C vs Team D    [checkbox]

我有一个按钮,当它被点击时它运行这个方法:

public void matchStart(View view){

    String selectedMatch = String.valueOf(((ListView) findViewById( R.id.listView )).getSelectedItemPosition());

    Toast.makeText(SelectTeams.this, selectedMatch, Toast.LENGTH_SHORT).show();


}

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

【问题讨论】:

  • 您正在获取列表位置,对于您的需要,请使用适配器的 getView 方法

标签: android listview


【解决方案1】:

您应该使用适配器的 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

        }
    });
    }


 }

【讨论】:

  • 我将如何实现这个,我对 android 比较陌生。
  • 这并不复杂,只需扩展 ArrayAdapter,并按照我的回答进行操作。我会编辑我的答案,所以会更详细一点。
  • 实际上这会比我试图解释的要好得多:vogella.com/tutorials/AndroidListView/article.html#arrayAdapter
  • 但是当按下按钮时,这是否能够检索选定的项目?而不是在按下实际项目时?
  • 是的,偏离航线。您可以对 ListView 项目做任何您想做的事情。
猜你喜欢
  • 2011-04-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-23
  • 2017-06-30
  • 1970-01-01
  • 2015-03-28
  • 1970-01-01
相关资源
最近更新 更多