在中心动态创建textview

Dynamically create textview in center

我有一个项目列表和一个相关布局。我想添加尽可能多的相对布局作为列表中的项目数和文本视图中的每个项目。 我的问题是,我无法将文本视图定位在布局的中心。 在我的代码下方

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

这里 rt 是动态创建的 RelativeLayout,textView 是动态创建的 TextView...noon 是我正在添加所有内容的 RelativeLayout。

textView.setGravity(Gravity.CENTER); 添加到 rt (RelativeLayout)

之前尝试使用 textView.setGravity(Gravity.CENTER);

试试这个:

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