Java – create viewholder final in custom listview adapter Android
•
Java
I have a listview with such a custom adapter
@Override public View getView(int position,View convertView,ViewGroup parent) { View view = convertView; ViewHolder viewHolder = new ViewHolder(); if (convertView == null) { view = inflator.inflate(R.layout.question_adapter_layout,parent,false); viewHolder.moreLayout = (LinearLayout) view.findViewById(R.id.extraOptions); viewHolder.reportBtn = (Button) view.findViewById(R.id.more_report); viewHolder.twitterBtn = (Button) view.findViewById(R.id.more_twitter); viewHolder.googleBtn = (Button) view.findViewById(R.id.more_google); viewHolder.fbBtn = (Button) view.findViewById(R.id.more_fb); viewHolder.deleteBtn = (Button) view.findViewById(R.id.more_delete); view.setTag(viewHolder); } else viewHolder = (ViewHolder) view.getTag(); viewHolder.moreBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Utilities.vibrate(mContext); if (viewHolder.moreLayout.getVisibility() == View.GONE) viewHolder.moreLayout.setVisibility(View.VISIBLE); else viewHolder.moreLayout.setVisibility(View.GONE); } });
Now change anything in onclicklistener I-E viewholder moreLayout. setVisibility(View.GONE); I need to make viewholder final, but later I will not be able to execute viewholder = (viewholder) view getTag();
How can I solve this problem?
Solution
Assign it to the final field before setonclicklistener
final ViewHolder viewHolderFinal = viewHolder; viewHolder.moreBtn.setOnClickListener(new View.OnClickListener()
And use viewholderfinal in onclicklistener
You can avoid creating a new viewholder every time you call getview
ViewHolder viewHolder = null; if (convertView == null) { viewHolder = new ViewHolder();
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码