Android - adding child view dynamically,set index ..etc

Add element dynamically

Linear Layout layout= (Linear Layout)findViewById(R.id.my_layout);

ImageButton saveBtn=new ImageButton(this);
saveBtn.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT)); saveBtn.setVisibility(1);//false ,0 for true

Adding as last child
layout.addView(saveBtn)

Adding in a perticular Index postion
layout.addView(saveBtn,10);

Bring Child To Front //not tested 
ViewGroup vg = ((ViewGroup) currentView.getParent());
int index = vg.indexOfChild(currentView);
  

vg.bringChildToFront(vg.getChildAt(0));



int optionId = someExpression ? R.layout.option1 : R.layout.option2;

    View C = findViewById(R.id.C);
    ViewGroup parent = (ViewGroup) C.getParent();
    int index = parent.indexOfChild(C);
    parent.removeView(C);
    C = getLayoutInflater().inflate(optionId, parent, false);
    parent.addView(C, index);
If you don't want to replace already existing View, but choose between option1/option2 at initialization time, then you could do this easier: set android:id for parent layout and then:
    ViewGroup parent = (ViewGroup) findViewById(R.id.parent);
    View C = getLayoutInflater().inflate(optionId, parent, false);
    parent.addView(C, index);
You will have to set "index" to proper value depending on views structure. You could also use a ViewStub: add your C view as ViewStub and then:
    ViewStub C = (ViewStub) findViewById(R.id.C);
    C.setLayoutResource(optionId);
    C.inflate();

0 comments:

Post a Comment