wazaminator
wazaminator

Reputation: 245

Android set gravity of a textview dynamically

I dynamically added horizontal layouts to my activity, and I am trying to put textviews inside of them.

The problem is, I can't manage to put some textviews To the right and some to the left.

I tried textview.setgravity, but it just changed the place of the text inside the textview instead of moving the textview itself.

Edit : here is some of my code to help you get an idea :

for(int i=0;i<nbelem;i++){          //génération des boutons des commandes
        layouts[i] = new RelativeLayout(this);
        layouts[i].setClickable(true);      //toute la zone est cliquable
        layouts[i].setId(i);
        layouts[i].setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, 150));


        Info[i] = new TextView(this);
        Info[i].setClickable(true); 
        Info[i].setId(i);
        Info[i].setText("Pizza 4 fromages x2 \n Pizza chevre x2");
        Info[i].setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.FILL_PARENT));

        layouts[i].addView(Info[i]);


        Numcom[i] = new TextView(this);
        Numcom[i].setClickable(true);
        Numcom[i].setId(i);
        Numcom[i].setText("n°1522");
        Numcom[i].setGravity(Gravity.RIGHT | Gravity.TOP);              
        Numcom[i].setTextSize(12);
        Numcom[i].setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,50));

Upvotes: 2

Views: 6534

Answers (2)

Daniel L.
Daniel L.

Reputation: 5140

It sounds that RelativeLayout may suit your needs and save you lots of nested LinearLayouts which are not recommended (performance wise).

Upvotes: 1

pzagor2
pzagor2

Reputation: 719

You have to set a layout gravity to the LinearLayout that contains your textview.

LayoutParams lp = new LayoutParams();
lp.gravity= Gravity.CENTER_HORIZONTAL; 
textview1.setLayoutParams(lp);

Be sure that you use LinearLayout.LayoutParams

Upvotes: 0

Related Questions