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();

Related Posts:

  • JEE : Login Form HTML - JS - MySQL =======MYSQL======= --Login--- C:\Program Files (x86)\MySQL\MySQL Server 5.6>mysql -u root -p Enter password: ****     //root mysql> CREATE DATABASE db; Query OK, 1 row affected (0.00 sec) mysql> U… Read More
  • Access Modifiers – Public, Private, Protected & Default Public - This is the least restrictive,accessible to entire project; Default - If no access modifier is specified in the declaration, accessible only within package,not accessible in other packages … Read More
  • Access Modifiers 2 – Static,Abstract,Final Static- Variables are calling Class variables. These members belong to the class not to the object,means values of these variables are not part of the object state.creating its while initiating class, … Read More
  • Abstract class class that is declared using “abstract” keyword;  may or may not include abstract methods ( has no body)and concrete methods (methods with body) ; we can  not allowed to create object of Abstract class, An … Read More
  • 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.WRA… Read More

0 comments:

Post a Comment