Modify XML features through Java

Asked

Viewed 270 times

2

I got the following RelativeLayout:

<RelativeLayout
            android:id="@+id/layout_avancado"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="#FF0000"
            android:layout_below="@+id/avancado_ttv"
            android:visibility="invisible"
            android:padding="10dp">
</RelativeLayout>

How can I modify attributes android:layout_below and android:visibility using Java? Is it possible?

2 answers

4


You need to use a class called Layoutparams, according to its layout (in this case, a Relativelayout). To add rules, you use the method addRule(), for example:

RelativeLayout mRelativeLayout = (RelativeLayout) findViewById(R.id.myRelativeLayout);

//Crie seu LayoutParams, passando como parametro seu Width e Height
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);

//Defindo como BELOW de algum componente, passando o mesmo como parametro
params.addRule(RelativeLayout.BELOW, R.id.yourComponentID);

/*Voce tambem pode definir margins, passando consecutivamente: left, top, right e bottom
* Detalhe que aqui, você passa em PIXELS.
*/
params.setMargins(8, 8, 8, 8);

//Para definir alinhamentos
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);

And now, setting these new parameters for your component:

mRelativeLayout.setLayoutParams(params);

Remember that when you put a new Layoutparams for your component, it replaces the rules you put via XML.

To set visibility, you simply need to:

//Aqui você pode utilizar VISIBLE, INVISIBLE e GONE
mRelativeLayout.setVisibility(View.INVISIBLE);

3

Dude, the visibility I know is possible yes. Just use findViewById in the layout and then use setVisibility, as follows:

findViewById(R.id.layout_avancado).setVisibility(View.VISIBLE);

The answer is incomplete, android:layout_bellow do not know how to do, someone else who knows responds.

  • I believe that for the layout_below just delete the old rule (removeRule) and add the new (addRule) in the LayoutParams and then call the requestLayout to update the interface.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.