sockeqwe
sockeqwe

Reputation: 15919

Android: Load Layout-File dynamically

I have a question about Android. Assume we have our main xml layout file, and defining there a place holder by using (for example) a FrameLayout. Also assume we have 2 other xml layout files displaying any content. So what I want to do is inject dynamically and programmtically one of the two layouts into the place holder. I know there exists the concept of Activitis, Fragments, ViewFlipper etc. But I find it comfortable to do things like this:

public class MainActivity extends Activity {

private FrameLayout placeHolder;
private View view1;
private View view2;


private RelativeLayout canvasPlaceHolder;
private PuzzleCanvas canvas;
private TextView infoLabel;


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // init gui
    setContentView(R.layout.activity_main);

    // Load layouts from xml
    LayoutInflater factory = getLayoutInflater();
    view1 = factory.inflate(R.layout.view1, null);
    view2 = factory.inflate(R.layout.view2, null);

}
}

with for example a Button on screen that does something like this:

@Override
public void onClick(View v) {
    placeHolder.removeView(view1);
    placeHolder.addView(view2);
}

For example to show a loadingAnimation (view2) instead of the normal content (view1) and so I can define both views comfortable and independent in xml.

Is the use of LayoutInflater commendable? What about the performance and memory management? What do you think about this? Is that a common way in Android?

Upvotes: 0

Views: 1894

Answers (2)

Vinay W
Vinay W

Reputation: 10190

Use 'include ' tag on the xml's frame layout to include both your xml's in the main xml. All you have to do is switch their ' VISIBILITY' through java according to ur app logic. eg: on a listener, set :

public void onClick(View v) {          
    innerView1.setVisibilty(View.INVISIBLE); 
    innerView2. setVisibilty(View.VISIBLE);  
}

Upvotes: 1

sam.wang.0723
sam.wang.0723

Reputation: 321

// Load layouts from xml LayoutInflater factory = getLayoutInflater();

view1 = factory.inflate(R.layout.view1, null);
view2 = factory.inflate(R.layout.view2, null);

Using LayoutInflater is ok, but I suggest not directly do this action in onCreate, if your layout is very complex, it might cause ANR (draw layout over 5 secs). Since these two views only appears after user reaction, I prefer to do with sendEmptyMessage with handler.

onCreate(...){
    handler.sendEmptyMessage(1);
}

private Handler handler = new Handler(){
    @Override
    public void handleMessage(final Message msgs) {
        if(msgs.what == 1){
            view1 = factory.inflate(R.layout.view1, null);
            view2 = factory.inflate(R.layout.view2, null);
        }
    }
}

Upvotes: 1

Related Questions