如何获取最后一个ListView项目位置

时间:2013-04-18 11:53:13

标签: android listview radio-button

我用radiobutton创建了一个listview。列表视图如下图所示: enter image description here

我的getView是:

public View getView(final int position, View convertView, ViewGroup parent) {
    ViewHolder holder = null;
    PaymentData rowItem = getItem(position);
    LayoutInflater mInflater = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    if (convertView == null) {
        convertView = mInflater.inflate(
                com.android.paypal.homeactivity.R.layout.list_item, null);
        holder = new ViewHolder();
        holder.radioBtn = (RadioButton) convertView
                .findViewById(com.android.paypal.homeactivity.R.id.rdb_payment_method);
        holder.btPaymentMethod = (Button) convertView
                .findViewById(com.android.paypal.homeactivity.R.id.bt_item_event);
        convertView.setTag(holder);
    } else
        holder = (ViewHolder) convertView.getTag();

    holder.radioBtn.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            if ((position != mSelectedPosition) && (mSelectedRB != null)) {
                mSelectedRB.setChecked(false);
            }

            mSelectedPosition = position;
            mSelectedRB = (RadioButton) v;
        }
    });

    if (mSelectedPosition != position) {
        holder.radioBtn.setChecked(false);
    } else {
        holder.radioBtn.setChecked(true);
        if (mSelectedRB != null && holder.radioBtn != mSelectedRB) {
            mSelectedRB = holder.radioBtn;
        }
    }

    holder.radioBtn.setText(rowItem.getRdbText());
    holder.btPaymentMethod.setText(rowItem.getBtText());
    return convertView;

}

我想在屏幕出现时自动检查最后一个radiobutton。我怎样才能做到这一点。

3 个答案:

答案 0 :(得分:6)

按住布尔值来说明用户是否自己选择了任何内容。设布尔值为userSelected = false;

现在你可以在getView()

if(position==getCount()-1 && userSelected==false)
    holder.radioBtn.setChecked(true);
else
    holder.radioBtn.setChecked(false);

在onItemClick中,当用户自己做出选择时,只需设置userSelected=true;

即可

答案 1 :(得分:4)

您的上一个职位是,int lastpostion = getcount() -1;其中getcount()是适配器类中的方法

答案 2 :(得分:0)

使用此方法

mListView.setOnScrollListener(new OnScrollListener() {

        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {

            if (scrollState == onScroll) {
                if (mListView.getLastVisiblePosition() == adapter.getCount() - 1) {
                    //Update new data here
                                            // and then, notify your adapter 
                                            adapter.notifyDataSetChanged();
                }
            }
        }

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

        }

    });