Search code examples
androidandroid-layouttextviewandroid-relativelayout

Dynamically create textview in center


I have a list of items and a relative layout. I want to add as many relative layouts as the no of items in list and textview in each on them. My problem is, I am not able to position the textview in the centre of the layout. Below in my code

for(int i = 0; i < Names.size(); i++)
    {                       
    textView = new TextView(this);
        textView.setText(Names.get(i)); 

         rt=new RelativeLayout(this);
        rt.setBackgroundResource(R.drawable.mednamedash);
        int curTextViewId = prevTextViewId + 1;
        int curRLId = prevRLId + 1;
        textView.setId(curTextViewId);
        rt.setId(curRLId);
        final RelativeLayout.LayoutParams params = 
            new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FILL_PARENT, 
                                            RelativeLayout.LayoutParams.WRAP_CONTENT);
        params.addRule(RelativeLayout.BELOW, prevTextViewId);
        rt.setLayoutParams(params);
        //textView.setLayoutParams(params);


        rt.addView(textView);
        textView.setGravity(Gravity.CENTER);
        prevTextViewId = curTextViewId;
        prevRLId=curRLId;
        noon.addView(rt, params);
    }        

Here rt is the dynamiclly created RelativeLayout and textView is the dynamically created TextView... noon is the RelativeLayout I am adding everything into.


Solution

  • Try this:

    final RelativeLayout.LayoutParams tvParams = 
            new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, 
                                            RelativeLayout.LayoutParams.WRAP_CONTENT);
    tvParams.addRule(RelativeLayout.CENTER_IN_PARENT);
    rt.addView(textView, tvParams);