setMargins(左,上,右,下); Android不起作用

时间:2014-12-04 16:46:47

标签: android textview margins

我有这个代码,但textview都没有Margin权利,我不知道为什么。 我添加了一些onCreate行来声明。 以及关于创建textview的功能。

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mLayout = (LinearLayout) findViewById(R.id.linearlayout);
    mEditText = (EditText) findViewById(R.id.input_materia);
    mButton = (Button) findViewById(R.id.add_materia);
    mButton.setOnClickListener(onClick());
    TextView textView = new TextView(this);
    textView.setText("New text");
/*
 * add textview from editext
 */
private OnClickListener onClick() {
    return new OnClickListener() {

        @Override
        public void onClick(View v) {
            mLayout.addView(createNewTextView(mEditText.getText().toString()));
        }
    };
}

private TextView createNewTextView(String text) {
    final LayoutParams lparams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    lparams.setMargins(0, 0, 30, 0);
    final TextView textView = new TextView(this);
    textView.setLayoutParams(lparams);
    textView.setText(text);
    textView.setGravity(Gravity.CENTER);
    return textView;
}

有些帮助?

1 个答案:

答案 0 :(得分:0)

您是否尝试过引用Relative Layout Params或Linear Layout Params,具体取决于您在XML中设置的内容?

RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.WRAP_CONTENT,
            RelativeLayout.LayoutParams.WRAP_CONTENT);

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.WRAP_CONTENT,
            LinearLayout.LayoutParams.WRAP_CONTENT);
相关问题