简体   繁体   中英

Android: Programmatically reading view IDs for LayoutParams

What I am trying to do is programmatically creating a row of buttons with a constraint view. I am creating two buttons and I want to have them next to each other without doing something to the .xml file, since the number of buttons can vary depending on the user.

I want to use something like (this code is part of an Activity):

ConstraintLayout layout = findViewById(R.id.layout);

Button btn1 = new Button(this);
Button btn2 = new Button(this);

ConstraintLayout.LayoutParams params1 = new ConstraintLayout.LayoutParams(ConstraintLayout.LayoutParams.WRAP_CONTENT,ConstraintLayout.LayoutParams.WRAP_CONTENT);
ConstraintLayout.LayoutParams params2 = new ConstraintLayout.LayoutParams(ConstraintLayout.LayoutParams.WRAP_CONTENT,ConstraintLayout.LayoutParams.WRAP_CONTENT);

layout.addView(btn1, 1, params1);   

params2.topToTop = btn1.getId();
params2.leftToRight = btn1.getId();

layout.addView(btn2, 2, params2);

Setting the two params2 values does not work because apparently I cannot really access the ID of button1. What would be a working solution to this? Things I have read and tried:

  • Using tags instead of ids
  • Accessing the buttons using an ArrayList of all the created buttons as a private member for the Activity
  • Giving some random id (that I have chosen) to the Views using setId()

Using something like this works, because I have predefined that btn3 in the xml file:

params2.topToTop = layout.findViewById(R.id.btn3).getId();
params2.leftToRight = layout.findViewById(R.id.btn3).getId();

But in all the other cases my btn2 just lands on top of btn1 (or rather on the top left edge of the layout)

Thank you in advance!

You can use the following method to generate view id programmatically:

private static final AtomicInteger nextGeneratedId = new AtomicInteger(10000);
public static int generateViewId() {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
        for (;;) {
            final int result = nextGeneratedId.get();
            // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
            int newValue = result + 1;
            if (newValue > 0x00FFFFFF) newValue = 10000; // Roll over to 10000, not 0.
            if (nextGeneratedId.compareAndSet(result, newValue)) {
                return result;
            }
        }
    } else {
        return View.generateViewId();
    }
}

call .setId(generatedId) for the buttons you create.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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