rel-s
rel-s

Reputation: 6138

Setting android TextViews and Buttons in the code

So I need to add TextViews andButtonsto my code **inside** the code itself like, dynamically adding them inside aforloop. My problem is setting thelayout_gravity` for both and getting them unique id's. Is there a way to add an id from within the code?

UPDATE

I need the id of the TextViews and Buttons to get into the R.id folder, is that even possible?

Upvotes: 1

Views: 98

Answers (2)

devunwired
devunwired

Reputation: 63293

No, it is not possible to generate ids at runtime that are still considered unique with respect to the rest of R.id, sorry. You CAN set the ID of a view to any value you like in Java code using the setId() method, however, here are some options for what you might consider:

  1. Set the ID of your dynamic views to values like 0, 1, 2, 3 or even 100, 101, 102, 103, etc. You may have noticed that the values generated by R.id always start with 0x7F so it would be VERY unlikely for you to pick values that would collide.
  2. Use the hashcode of the view, a la view.setId( view.hashCode() ) to generate a more unique ID. This is what RadioGroup does when its children don't have an ID.
  3. You CAN generate R.id values ahead of time that are not attached to views by creating a res/values/ids.xml (see SDK article). These can then be added with view.setId(R.id.xxx) at runtime.

As far as your layout_gravity problem, this is probably because values prefixed with layout_ in XML are LayoutParams and not properties of the actual view. You need to add that value to a LayoutParams object and set those params on your new view, a la:

Button button;
LinearLayout layout;
LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
lp.gravity = Gravity.CENTER;

//Option #1 to add
layout.addView(button, lp);

//Option #2 to add
button.setLayoutParams(lp);
layout.addView(button);

HTH

Upvotes: 2

Krishnakant Dalal
Krishnakant Dalal

Reputation: 3578

// sets button properties
    btn = new ImageButton(this);
    btn.setId(id);
    btn.setTag(Image_Name);

    btn.setBackgroundColor(Color.TRANSPARENT);
    btn.setAdjustViewBounds(true);

    btn.setImageBitmap(bmp);

    btn.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {

        // Implement Click Listener

        }
    });

You can any component like these.

Upvotes: 2

Related Questions