0

I have a block of Views containing an ImageView, a Button and a TextView. I want to create this block dynamically in the Java code. Is there a way to define this block in XML, alter the src/text attributes and append it to my current layout?

Thanks!

Ron

1 Answer 1

1

I use the following technique:

<!-- content.xml -->
<merge>
  <ImageView android:id="@+id/image />
  <Button android:id="@+id/button />
  <TextView android:id="@+id/text />
</merge>

Then inflate using a LayoutInflater:

View block = inflater.inflate(R.layout.content, root, attach);
(TextView) textView = (TextView) block.findViewById(R.id.text);
textView.setText(text);

I found this especially useful when you write a custom View extending a ViewGroup (eg LinearLayout or RelativeLayout) and you want to define the content in a declarative XML. For example

public class MyWidget extends LinearLayout {

  // Invoked by all of the constructors
  private void setup() {
    Context ctx = getContext();
    inflate(ctx, R.layout.content, this);
    ((TextView) findViewById(R.id.text)).setText(
        ctx.getString(R.string.hello_world)
    );
  }
}

A possible variation is using a Layout instead of <merge> if you don't need it. The LayoutInflater can be obtained by Activity.getLayoutInflater() or by any Context via getSystemService() (you have to cast the result to a LayoutInflater object in the latter case.

Sign up to request clarification or add additional context in comments.

3 Comments

if i use this block several times...how do i avoid having trouble addressing the views via id? the id/image will be there several times, wont it?
The id is just an identifier to find views. It doesn't even need to be unique inside a hierarchy. Nothing happens when two views have the same ID. The only problem is that when you invoke View.findViewById(int) and two or more views with the same ID exist, because in this case you may not find what you were looking for (you may want to use setTag(Object) in some circumstances). However with my code you won't have any problem, because the inflater returns the last created hierarchy, and you can call findViewById on this hierarchy, and in content.xml the aren't duplicate ID
hm...it seems that only one block is appended... any ideas why?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.