2013-10-10 37 views
1

我試圖使用xml分割屏幕。代碼爲 請嘗試此xml ..我需要使用相同的編程方式。如何在不使用xml的情況下在android中動態分割屏幕

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
       android:layout_width="match_parent" 
       android:layout_height="match_parent" 
       android:orientation="vertical" > 

    <LinearLayout 
      xmlns:android="http://schemas.android.com/apk/res/android" 
      android:layout_width="318dp" 
      android:layout_height="0dp" 
      android:layout_weight="1" 
      android:orientation="horizontal" 
      android:background="@android:color/holo_purple"> 

     <LinearLayout 
       xmlns:android="http://schemas.android.com/apk/res/android" 
       android:layout_width="318dp" 
       android:layout_height="match_parent" 
       android:layout_weight="1" 
       android:orientation="horizontal" android:background="@android:color/holo_purple"> 

     </LinearLayout> 

     <LinearLayout 
       xmlns:android="http://schemas.android.com/apk/res/android" 
       android:layout_width="318dp" 
       android:layout_height="match_parent" 
       android:layout_weight="1" 
       android:orientation="horizontal" 
       android:background="@android:color/holo_blue_dark"> 
     </LinearLayout> 
     <LinearLayout 
       xmlns:android="http://schemas.android.com/apk/res/android" 
       android:layout_width="318dp" 
       android:layout_height="match_parent" 
       android:layout_weight="1" 
       android:orientation="horizontal" 
       android:background="@android:color/darker_gray"> 
     </LinearLayout> 
     </LinearLayout> 

    </LinearLayout> 

但是,我需要以編程方式分割屏幕。任何人都可以提供解決方案嗎?

+1

是否有您所遇到的XML的特定部分在代碼中重新創建問題?你能提供迄今爲止所做的任何代碼嗎? – Matt

+0

@ user2145222:看到這張圖..http://www.mediafire.com/view/myfiles/#m6l4q71av9x43h7我在xml中做過...但現在我需要它在編程方式在活動 –

+0

抱歉,但不能回答我的的問題。我不會對你想要做的事情感到困惑,我只是想知道你在哪裏陷入困境。據推測,你至少有一些代碼來創建一些線性佈局? – Matt

回答

0

通過分割屏幕你的意思是將佈局寬度,那麼你可以按照以下嘗試..

// gets the screen width 
      float screenWidth = getWindowManager() 
        .getDefaultDisplay().getWidth(); 

你可以從上面的代碼獲取屏幕寬度..

和屏幕高度

// gets the screen height 
     float screenHeight = getWindowManager() 
       .getDefaultDisplay().getHeight(); 

然後你所要做的就是使用LayoutParams設置佈局寬度。

LinearLayout view = (LinearLayout) findViewById(R.id.ur_layout_id); 
view.setLayoutParams(new LinearLayout.LayoutParams((int) screenWidth/3, 
        (int) screenHeight , 1f)); 

您可以設置layoutwidth通過screenWidth/2通過screenWidth/3一半來劃分屏幕,在3件等.. 希望這有助於..

+1

假設這可以解決問題,使用weight屬性而不是使用窗口管理器會不會更容易?例如:在水平線性佈局父級中使用的setLayoutParams(新的LinearLayout.LayoutParams(0,LayoutParams.MATCH_PARENT,1))會平均分割屏幕寬度。 Dinesh甚至在提供的xml中的第二個線性佈局中使用它(只是垂直)也許我錯過了一些東西? – Matt

相關問題