Harsh Shah Harsh Shah - 3 months ago 28
Android Question

How to get view and holder object outside getView method?

I have adapter and fragment.

Consider this scenario :


  1. Adapter has Edit Text

  2. By default edit text is not editable

  3. Fragment has one edit icon

  4. On click of edit icon adapter's edit text should became editable



Here is fragment code:

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


here is Adapter code:

@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?
}

Answer

inside your adapter

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();     
}

you're asking to get the view outside getView() method but I wouldn't advise it, the whole point of having a ListView/RecyclerView is not having to deal with those views individually