android TextView使用代码设置边距和背景

时间:2011-06-12 05:39:02

标签: android textview

在Android活动中......如何使用代码而不是XML来执行以下操作?

<TextView android:background="#0000ff" android:layout_margin="2dip"/>

我还需要正确对齐文字......

坚持了一段时间=(如果有人可以提供帮助

感谢

更新

我尝试了以下代码

    RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams( 
            RelativeLayout.LayoutParams.FILL_PARENT,                
            RelativeLayout.LayoutParams.FILL_PARENT);                
            //250);

    lp.setMargins(5,5,5,5);

我做了

row.addView(t1, lp);
row.addView(t2);
row.addView(t3);
row.addView(t4);

我也尝试过LinearLayout

但由于某些原因t1根本不再显示....

2 个答案:

答案 0 :(得分:2)

这里是如何编写textView:

    mTextView = new TextView(this);
    mTextView.setGravity(Gravity.CENTER_VERTICAL);       
    mTextView.setText(R.string.instructions);
    mTextView.setTextColor(0xFF000000);
    mTextView.setPadding(20, 8, 8, 20);

    mTextView.setTextSize(TypedValue.COMPLEX_UNIT_PT, 8);

    mScroll = new ScrollView(this);
    mScroll.setScrollbarFadingEnabled(false);
    mTextPane = new RelativeLayout(this);
    mTextPane.setVisibility(View.GONE);
    //mScroll.setVisibility(View.GONE);

    mScroll.addView(mTextView);
    mTextPane.addView(mScroll);

    Resources res = getResources();
    //Drawable drawable = res.getDrawable(R.drawable.text_pane_feather2);
    Drawable drawable = res.getDrawable(R.drawable.text);
    mTextPane.setBackgroundDrawable(drawable);

    //RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams( 420, 420 );
    RelativeLayout.LayoutParams lp = 
        new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.WRAP_CONTENT,
                //RelativeLayout.LayoutParams.WRAP_CONTENT);
                250);

    lp.setMargins(0,0,0,30);
    lp.addRule(RelativeLayout.CENTER_HORIZONTAL );
    lp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);

    layout.addView(mTextPane, lp);

答案 1 :(得分:1)

尝试TextViews setBackgroundColour()方法。 要设置布局参数,请使用MarginLayoutParams类中的setMargins(int,int,int,int)。 有关详细信息,请参阅文档: View.setBackgroundColourLayout Params