3

我有custom_layout.xml:獲取計算器的錯誤,而試圖誇大自定義視圖

<?xml version="1.0" encoding="utf-8"?> 

<com.example.MyCustomLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:orientation="vertical" > 

<!-- different views --> 

</com.example.MyCustomLayout> 

而其類:

public class MyCustomLayout extends LinearLayout { 

public MyCustomLayout(Context context, AttributeSet attrs) { 
    super(context, attrs); 

    LayoutInflater.from(context).inflate(R.layout.custom_layout, this, true); 
    setUpViews(); 
    } 
//different methods 
} 

和活動,其中包括這樣的佈局:

public class MyActivity extends Activity { 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.my_activity); 

    setUpViews(); 
} 

和my_activity.xml:

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

<LinearLayout 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:orientation="vertical" > 

    <com.example.MyCustomLayout 
     android:id="@+id/section1" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:orientation="vertical" /> 
    <com.example.MyCustomLayout 
     android:id="@+id/section2" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:orientation="vertical" /> 

</LinearLayout> 

所以,我當我從刪除註釋塊一個問題:LayoutInflater.from(context).inflate(R.layout.custom_layout, this, true);走在圖形模式my_activity.xml。 Eclipse認爲然後崩潰。它看起來像試圖多次膨脹我的自定義視圖,但我不明白爲什麼。我'在錯誤日誌中收到此錯誤,當我重新啓動日食:java.lang.StackOverflowError

+0

它在電話中工作嗎? – dmon

+0

noooooooooooooo – bluebyte

回答

4

在你custom_layout.xml另一個佈局(例如LinearLayout)取代<com.example.MyCustomLayout

<?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="wrap_content" 
    android:orientation="vertical" > 

<!-- different views --> 

</LinearLayout> 

甚至更​​好(在MyCustomLayout類,並設置orientation)使用merge標籤。現在當Android加載my_activity.xml它會找到您的自定義View,它會實例化它。當您的自定義視圖將被實例化時Android將使構造函數中的custom_layout xml文件膨脹。當發生這種情況時,它將再次找到<com.example.MyCustomLayout ...(來自剛填充的custom_layout.xml),這導致MyCustomLayout被再次實例化。這是一個遞歸調用,它最終會拋出StackOverflowError

+0

太棒了!謝謝 – bluebyte

0

此行

LayoutInflater.from(context).inflate(R.layout.custom_layout, this, true); 
在構造函數的自定義佈局對象

的存在造成的自立呼叫的無限遞歸,溢出堆棧。

你沒有理由這麼做。

也許你最好打賭是挖掘一個別人的工作自定義佈局類的例子。

+0

沒有這一行 - 我試圖查找時得到空BitById – bluebyte

+0

也許,但這不是解決它的正確方法。我建議你找一個自定義佈局的例子作爲指導它應該如何完成的機制。 –