如何在getView方法之外获取视图和持有者对象?

时间:2016-08-22 14:50:26

标签: android listview android-adapter android-viewholder android-adapterview

我有适配器和片段。

考虑这种情况:

  1. 适配器具有编辑文本

  2. 默认情况下,编辑文字不可编辑

  3. 片段有一个编辑图标
  4. 点击编辑图标适配器的编辑文字应该可以编辑
  5. 这是片段代码:

    editIcon.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Adapter.makeEditTextEditable();
        }
    });
    

    这里是适配器代码:

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        ViewHolder holder = null;
    
        if (convertView == null) {
            convertView = inflater.inflate(R.layout.layout, null);
            holder = new ViewHolder();
            holder.EditText = (EditText) convertView.findViewById(R.id.edit_text);
    
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
    }
    
    
    // This is method i am calling from fragment to make editText editable 
    public void makeEditTextEditable() {
        // How do i get holder object and view object here? OR
        // How do i make edit text editable from this method?
    }
    

1 个答案:

答案 0 :(得分:3)

适配器内的

boolean mEditTextEditable = false;

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    ViewHolder holder = null;

    if (convertView == null) {
        convertView = inflater.inflate(R.layout.layout, null);
        holder = new ViewHolder();
        holder.EditText = (EditText) convertView.findViewById(R.id.edit_text);

    } else {
        holder = (ViewHolder) convertView.getTag();
    }    

    holder.EditText.setEnabled(mEditTextEditable);
}

public void setEditTextEditable(boolean editable) {
    if(editable == mEditTextEditable) return;

    mEditTextEditable = editable;
    notifyDatasetChange();     
}

你要求在getView()方法之外获取视图,但我不建议,让ListView / RecyclerView不必单独处理这些视图的重点