2014-03-05 74 views
0

我在RelativeLayout中有一個linearLayout。我需要能夠根據屏幕尺寸動態設置線性佈局的高度。我有一些困難。 我怎麼能做到這一點?在RelativeLayout中動態設置LinearLayout高度/寬度

MAIN:

public class MainActivity extends Activity { 

LinearLayout L; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    L=(LinearLayout)findViewById(R.id.top); 

    L.setLayoutParams(new LinearLayout.LayoutParams(1080, 400)); 
} 

} 

XML:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:tools="http://schemas.android.com/tools" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 

tools:context=".MainActivity" > 

<LinearLayout 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:background="#fff" 
    android:id="@+id/top" 
    android:orientation="horizontal" > 

    <TextView 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="@string/hello_world" /> 
</LinearLayout> 

+0

有什麼難度/問題? –

+0

@JustinJasmann我得到這個錯誤-java.lang.ClassCastException:android.widget.LinearLayout $ LayoutParams不能轉換爲android.widget.RelativeLayout $ LayoutParams at android.widget.RelativeLayout $ DependencyGraph.findRoots(RelativeLayout.java:1722) – Samantha

回答

3

當您設置佈局參數,可以它需要是的父母。

開關:

L.setLayoutParams(new LinearLayout.LayoutParams(1080, 400)); 

要:

L.setLayoutParams(new RelativeLayout.LayoutParams(1080, 400)); 
+0

太棒了!快樂編碼:) –

0
在你的LinearLayout

,只需設置

android:layout_height="0dp" 
android:layout_weight="1" 
+0

不起作用 – Samantha

+0

我認爲你必須刪除L =(LinearLayout)findViewById(R.id.top); L.setLayoutParams(new LinearLayout.LayoutParams(1080,400)); – s4m0k

+0

@ s4m0k你如何在代碼中做到這一點? –

0

賈斯汀回答

L.setLayoutParams(new RelativeLayout.LayoutParams(1080, 400)); 

你也可能需要,如果你已經設置了佈局

L.requestLayout();