How to get the id from programmatically linear layout item

I don't know how to get the id of an item in a programmatically created linear layout. I want to "catch" the right id of an button and associate that with fields.

LinearLayout layout = (LinearLayout)  findViewById(R.id.content_doodle_linearlayout3);
    layout.setOrientation(LinearLayout.VERTICAL);  


    String[] data = {"1","2","3","4"};
    String[] users = {"1","2","3"};


 for (int i = 0; i < users.length; i++) {
        row = new LinearLayout(this);
        row.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));

        text = new TextView(this);
        text.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
        text.setText("Name " + (i));
        text.setId(1000 + i);

        row.addView(text);
        int ergebnis = -1;
        for (int j = 0; j < daten.length; j++) {
            CheckBox btnTag = new CheckBox(this);
            btnTag.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
            //btnTag.setText("Button " + (j + 1 + (i * 4)));
            btnTag.setId(j + 1 + (i * 4));

            row.addView(btnTag);
        }

        layout.addView(row);
    }

The Buttons can't not be found, because there "isn't" a (R.id.{XML-Field}). How can i "find" the clicked button from the specific row. Do i have to code every button?

1 answer

  • answered 2019-06-25 08:43 Alexei Artsimovich

    You can set a specified tag for each child view in your layout in this way:

    View childView = ...;
    childView.setTag("Some tag");
    

    And then in your onClickListener:

    child.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Object tag = view.getTag();
            if (tag instanceof String) {
                String stringTag = (String) tag;
                if (stringTag.equals("Some tag") {
                    // do something
                }
            }
        }
    });