2014-12-04 155 views
1

我有這個代碼,但textview都沒有保證金的權利,我不知道爲什麼。 我添加了一些onCreate行聲明。 和有關創建textview的功能。setMargins(left,top,right,bottom); Android不起作用

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

有些幫助嗎?

回答

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

對不起,我錯了。 我刪除了「最終的LayoutParams lparams =新的LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);」 並添加了線性佈局參數的參考,現在工作。 但現在如何線性佈局需要代碼?所有線性佈局? – Mario 2014-12-04 17:27:09

+0

其確定,我犯了這個錯誤數百次。如果它是相對佈局,則可以引用另一個。你可以用Relative而不是Linear來做同樣的事情。如果您在佈局中有佈局,則此方法有效。所以如果你有一個線性作爲父母和一個親屬作爲孩子,反之亦然。 – Dacotah 2014-12-04 17:37:48

+0

那麼LinearLayout.LayoutParams從活動中獲取所有的LinearLayout? Ty尋求幫助;) – Mario 2014-12-04 17:40:18