Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android programmatically include layout (i.e. without XML)

So I've created an Activity subclass called CustomTitlebarActivity. Essentially, each main activity in my app will have a custom titlebar with many common features such as a Home button, a title, a search button, etc. In my current implementation, I am still explicitly using an include statement in the layout XML for each CustomTitlebarActivity:

<include layout="@layout/titlebar" /> 

It seems natural that I should be able to do this within CustomTitlebarActivity. I have two questions: What code can replace this include tag, and where should I put the code? (My first instinct would be to put it in CustomTitlebarActivity's setContentView method.)

On a related note, I would appreciate insight into better ways to reuse android UI code (even if, per se, the titlebars need to vary slightly between activities.)

like image 513
Jon Willis Avatar asked Jul 07 '10 14:07

Jon Willis


2 Answers

I met this issue too, and I just solved it now. I think my solution is easier:

  1. create a inflater:

    LayoutInflater inflater = (LayoutInflater)      this.getSystemService(LAYOUT_INFLATER_SERVICE); 
  2. inflate the child layout:

    View childLayout = inflater.inflate(R.layout.child,             (ViewGroup) findViewById(R.id.child_id)); 
  3. add it into parent:

    parentLayout.addView(childLayout); 

It's done, enjoy it!

like image 135
acoustic Avatar answered Oct 12 '22 16:10

acoustic


Personally, I'd probably write my Activity subclass to always setContentView to a layout file containing a vertical fill_parent LinearLayout containing only my title bar:-

<LinearLayout android:id="@+id/custom_titlebar_container"     android:orientation="vertical"     android:layout_width="fill_parent"     android:layout_height="fill_parent">    <!--titlebar here--> </LinearLayout> 

Then I'd define an abstract getContentAreaLayoutId() method in CustomTitlebarActivity that returns the layout ID of the content below the titlebar for each subclass; the base onCreate() of CustomTitlebarActivity would then just call

setContentView(R.layout.custom_titlebar_activity_frame_from_above); View.inflate(this, getContentAreaLayoutId(), findViewById(R.id.custom_titlebar_container)); 

Alternatively, you could have your abstract method for getting the content area return a View rather than an int, giving you more flexibility to construct your views dynamically (but forcing you to inflate them yourself in the simple just dump this XML layout here case).

like image 37
Yoni Samlan Avatar answered Oct 12 '22 18:10

Yoni Samlan