Reputation: 6138
So I need to add TextViews
andButtons
to my code **inside** the code itself like, dynamically adding them inside a
forloop. My problem is setting the
layout_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
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:
view.setId( view.hashCode() )
to generate a more unique ID. This is what RadioGroup
does when its children don't have an ID.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
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