简体   繁体   English

如何处理android中动态创建的按钮?

[英]How to handle dynamically created buttons in android?

I am new to android development, in fact its my first application.我是 android 开发的新手,实际上它是我的第一个应用程序。 I have created a dynamic layout in my project based on Json.我在基于 Json 的项目中创建了一个动态布局。 Each object includes an "id" key and some more string keys.每个对象都包含一个“id”键和一些更多的字符串键。 every object in my json should be transformed to a cardview inside a recylcerview and each cardview has a button.我的 json 中的每个对象都应该转换为 recylcerview 中的 cardview,并且每个 cardview 都有一个按钮。 My problem is handling these dynamic buttons.我的问题是处理这些动态按钮。 Is it possible to determine which button was clicked?是否可以确定单击了哪个按钮?

View.id is an integer, and you shouldn't set arbitrary values to it if the View is generated dinamically, what you can use though is View.tag . View.id是一个整数,如果View是动态生成的,则View.tag设置任意值,但您可以使用的是View.tag So you can assign the id defined in the JSON to tag and then check the tag value when the View is clicked.所以你可以将 JSON 中定义的 id 分配给tag ,然后在View被点击时检查tag值。 Eg例如

val view1 = View(context)
view1.tag = "id from JSON 1"
view1.setOnClickListener(this::onViewClicked)

val view2 = View(context)
view2.tag = "id from JSON 2"
view2.setOnClickListener(this::onViewClicked)

// ...

private fun onViewClicked(view: View){
    val jsonId = view.tag as? String
    // ...
}

If your min sdk level at least 17, another option would be to generate ids dinamically with View.generateViewId() and store them in a Map together with your JSON ids如果您的最小 sdk 级别至少为 17,另一种选择是使用View.generateViewId()动态生成 id,并将它们与您的 JSON id 一起存储在Map

Use a Tag to differentiate the buttons.使用标签来区分按钮。 Add OnClickListener to all Button and set different String tag to button.OnClickListener添加到所有Button并为Button设置不同的 String 标签。

button.setOnClickListener(this);

Add ClickListener添加点击监听器

 @Override
  public void onClick(View view){
    String tag = (String)view.getTag();
    if(tag.equals(tag1)){
      // action here 
    }
    //.......
    .....
 }

Yeah pretty straight, all you have to do is to give them a unique id I assume you must have a JSON array for dynamic buttons creation.是的,很直接,你所要做的就是给他们一个唯一的 id 我假设你必须有一个 JSON 数组来创建动态按钮。

sample code示例代码

public Button createButton(Context context,String text,int buttonNo){
  //here set the properties
  Button bt = new Button(context);
  bt.setText(text);
  bt.setId(buttonNo);
  bt.setTag(buttonNo);
  bt.setOnClickListener(new View.OnClickListener(){
    @Override
    public void onClick(View view){
       //handle the button click, unique id , you can use to differentiate
       int id = view.getId();

    }

  });
  return bt;
}

call this above method in for loop or as many times you want to create.在 for 循环中调用上述方法或多次调用。 you can also set a tag as mentioned above to store more information.您还可以设置如上所述的标签来存储更多信息。

Finally I put the OnClickListener in onBindViewHolder event inside my customAdapter class as below:最后,我将 OnClickListener 放在我的 customAdapter 类中的 onBindViewHolder 事件中,如下所示:

public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.ViewHolder> implements View.OnClickListener {

private Context context;
private List<MyData> my_data;

public CustomAdapter(Context context, List<MyData> my_data) {
    this.context = context;
    this.my_data = my_data;
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

    View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.card,parent,false);

    return new ViewHolder(itemView);
}

@Override
public void onBindViewHolder(final ViewHolder holder, int position) {
        holder.match_date.setText(my_data.get(position).getMatch_date());
        holder.home_name.setText(my_data.get(position).getHome_name());
        holder.away_name.setText(my_data.get(position).getAway_name());

        holder.button.setId(my_data.get(position).getId());
        holder.button.setTag(my_data.get(position).getStringId());
        holder.button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int intHomeGoals = Integer.parseInt(holder.edtHomeGoals.getText().toString());
                int intAwayGoals = Integer.parseInt(holder.edtAwayGoals.getText().toString());
                if (intHomeGoals == intAwayGoals)
                {
                    Toast.makeText(context, "00000", Toast.LENGTH_SHORT).show();
                }
            }
        });
        Glide.with(context).load(my_data.get(position).getHome_logo()).into(holder.home_logo);
        Glide.with(context).load(my_data.get(position).getAway_logo()).into(holder.away_logo);
}

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

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