ListView带有适配器内的专用按钮

时间:2016-08-26 15:32:03

标签: java android listview adapter

这是自定义类

public class TextWithButton{
protected String playerName;

public TextWithButton(String playerName){
    this.playerName=playerName;
}

这是自定义适配器

public class TextWithButtonAdapter extends ArrayAdapter<TextWithButton>{
Context context;
int layoutResourceId;
ArrayList<TextWithButton> data = null;
boolean isAddable;

public TextWithButtonAdapter(Context context, int layoutResourceId, ArrayList<TextWithButton> data, boolean isAddable) {
    super(context, layoutResourceId, data);
    this.layoutResourceId = layoutResourceId;
    this.context = context;
    this.data = data;
    this.isAddable = isAddable;
}

@Override
public void add(TextWithButton object)
{
    super.add(object);
}

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

    if(row == null)
    {
        LayoutInflater inflater = ((Activity)context).getLayoutInflater();
        row = inflater.inflate(layoutResourceId, parent, false);

        holder = new TextWithButtonHolder();
        holder.playerNameText = (TextView)row.findViewById(R.id.player_name);
        holder.processPlayerFab = (FloatingActionButton)row.findViewById(R.id.process_player);

        row.setTag(holder);
    }
    else
    {
        holder = (TextWithButtonHolder)row.getTag();
    }

    TextWithButton textWithButton = data.get(position);
    holder.playerNameText.setText(textWithButton.playerName);
    if(isAddable)
    {
        holder.processPlayerFab.setImageResource(android.R.drawable.ic_menu_add);
        holder.processPlayerFab.setBackgroundColor(context.getResources().getColor(android.R.color.holo_green_light));
    }
    else
    {
        holder.processPlayerFab.setImageResource(android.R.drawable.ic_menu_delete);
        holder.processPlayerFab.setBackgroundColor(context.getResources().getColor(android.R.color.holo_red_light));
    }

    return row;
}

static class TextWithButtonHolder
{
    TextView playerNameText;
    FloatingActionButton processPlayerFab;
}

我正在尝试从适配器外部为该FloatingActionButton设置OnClickListener,因为我想为它实现多种功能。例如,我想在某个类中有两个适配器,在单击它们时它们会调用两个不同的函数。我还想避免使用ListView的setOnItemClickListener。

1 个答案:

答案 0 :(得分:0)

好吧,如果我明白你很想从容器视图中访问floatingactionbutton来专门设置onclicklistner。

执行此操作的方法将是一种for循环,通过说明您在globactionbutton中放置的一些数字标记。如

floatingbutton.setTag("tag" + position);

然后在某个地方访问按钮,可能在for循环中遍历listview,在其容器类中添加特定的onclick效果。

(FloatingActionButton) listview.findViewWithTag("tag" + (int));

这将允许您将onclicklisteners添加到其容器类的浮动操作按钮。

除非我误解了这个问题。