简体   繁体   English

如何将计数器值分配给可扩展列表视图按钮

[英]how to assign counter value to expandable list view button

I have expandable list view and each one of view has button. 我有可扩展的列表视图,每个视图都有按钮。 I need to set a tag to each of the button like button1(count 0), button1(count 1), button1(count 2)....... I tried incrementing count each time but it is setting some random counter value. 我需要为每个按钮(例如button1(计数0),button1(计数1),button1(计数2))设置一个标记。......我每次都尝试递增计数,但是它设置了一些随机计数器值。

I am suspecting that I am doing counter++ in wrong place please some one suggest me where I can increment the counter value. 我怀疑我在错误的地方做计数器++,请有人建议我在哪里可以增加计数器值。

Universally assigning counter: 通用分配计数器:

int counter = 0;

In getChildView() method 在getChildView()方法中

 @Override
public View getChildView(final int i, final int i1, boolean b, View view, ViewGroup viewGroup) {
   if (view == null) {
        holder = new ViewHolder();
        LayoutInflater parentInflater = (LayoutInflater) mctx.getSystemService(mctx.LAYOUT_INFLATER_SERVICE);
        view = parentInflater.inflate(R.layout.itemname_child_layout, null);
        holder.button = view.findViewById(R.id.childrecordbtn);
 } else {
        holder = (ViewHolder) view.getTag();
 }

 holder.button.setTag(counter);

 holder.button..setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
          int tag = view.getTag();
          Log.i("Tag Value = ",tag);
        }
 }
 counter++;
 return view;
}

Above code returning some random values after button click. 上面的代码在单击按钮后返回一些随机值。

Output : 输出:

Button1 : "Tag Value : 24"
Button2 : "Tag Value : 25"
Button3 : "Tag Value : 113"

Take a look at the definitation of getChildView() : 看看getChildView()

getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent)

That means in your code, i is the groupPosition and i1 is the childPosition . 这意味着在您的代码中, igroupPositioni1childPosition You should only rely on these parameters to determine the content of each row rather than using an external counter. 您应该仅依靠这些参数来确定每一行的内容,而不是使用外部计数器。

You can get an one-dimensional array index by the follow calculation: 您可以通过以下计算获得一维数组索引:

int sum = 0;
for(int j = 0;j < i; j++)
{
       sum += getChildrenCount(j);
}
final int arrayIndex = sum + i1;
holder.button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Log.i("Tag Value = ",arrayIndex);
        }
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM