3

我有一个带有这样的自定义适配器的 listView

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

现在更改 onClickListener 中的任何内容,即viewHolder.moreLayout.setVisibility(View.GONE);我需要使 viewHolder 最终但我将无法做到viewHolder = (ViewHolder) view.getTag();

我该如何解决这个问题?

4

2 回答 2

11

将其分配给 setOnClickListener 之前的最终字段

final ViewHolder viewHolderFinal = viewHolder;
viewHolder.moreBtn.setOnClickListener(new View.OnClickListener()

viewHolderFinal在 onClickListener 内部使用

您可以避免在每次调用 getView 时创建新的 ViewHolder。

ViewHolder viewHolder = null;

    if (convertView == null)
    {
      viewHolder = new ViewHolder();
于 2013-06-27T09:23:14.660 回答
1

将 onClickListener 放在 ViewHolder 里面,视图 moreLayout 也放在 ViewHolder

    class ViewHolder {

    public View more_Layout;

    public Button reportBtn;
    public Button twitterBtn;
    public Button googleBtn;
    public Button fbBtn;
    public Button deleteBtn;


    public ViewHolder(){

    moreBtn.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) 
      {
        Utilities.vibrate(mContext);
        if (moreLayout.getVisibility() == View.GONE)
            moreLayout.setVisibility(View.VISIBLE);
        else
            moreLayout.setVisibility(View.GONE);
      }
    });

}

于 2015-01-05T15:05:32.287 回答