【问题标题】:Android: control listview item from external button clickAndroid:从外部按钮单击控制列表视图项
【发布时间】:2018-02-13 07:18:52
【问题描述】:

我的片段中有一个下一步按钮和列表视图。 当我单击外部“下一步”时,我必须更改列表项的背景, 第二次单击它应该转到列表中的下一个项目并更改背景。 当我单击下一步时,它位于最后一行,它应该来到第一行项目。

下面是我的简单 ArrayAdapter

public class MyListAdapter extends ArrayAdapter<String> {

    private List<String> list;
    private Context mContext;

    public MyListAdapter(Context context, int resource,
            int textViewResourceId, List<String> objects) {
        super(context, resource, textViewResourceId, objects);
        list = objects;
        mContext = context;
    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return list.size();
    }

    @Override
    public String getItem(int position) {
        // TODO Auto-generated method stub
        return super.getItem(position);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        View mView = super.getView(position, convertView, parent);
        return mView;
    }
}

【问题讨论】:

    标签: android listview android-arrayadapter


    【解决方案1】:

    一种方法是使用getChildAt() 您应该维护当前索引 如果用户点击下一步 ->

    private int index = 0;
    public void nextButtonClicked(){
        updateViewAt(index,false)
        if(index==(listView.getCount()-1)){
          index = 0
        }else{
          index++
       }
        updateViewAt(index,true)
    }
    
    private void updateViewAt(int index,boolean isSelected){
        View v = listView.getChildAt(index - 
            listView.getFirstVisiblePosition());
    
        if(v == null)
           return;
    
        TextView textView= (TextView) v.findViewById(R.id.text_view);
    if(isSelected){
    //TODO if view is selected functionality
    }else{
    //  TODO if view is NOT selected functionality
    }
    }
    

    【讨论】:

    • 谢谢。几乎没有修改就得到了我的预期结果。
    【解决方案2】:

    - 维护一个指针(从0开始),记录改变背景的listview item的位置。

    下次点击时,如果小于列表左侧,则加1并调用notifydatasetchanged,否则设置为0并调用notifydataSetChanged。

    -在适配器类中,在getview中,如果位置小于等于指针,则改变背景else设置为默认值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-26
      • 2020-07-26
      • 1970-01-01
      • 2013-09-12
      相关资源
      最近更新 更多