2015-08-28 47 views
0

mainactivity.xml膨脹佈局無法在Android的

<FrameLayout 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" 
    android:paddingLeft="@dimen/activity_horizontal_margin" 
    android:paddingRight="@dimen/activity_horizontal_margin" 
    android:paddingTop="@dimen/activity_vertical_margin" 
    android:paddingBottom="@dimen/activity_vertical_margin" 
    tools:context=".MainActivity" 
    android:background="#ff0" 
    android:id="@+id/myframe" 
    > 


    <LinearLayout 
     android:orientation="horizontal" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:layout_gravity="left|top" 
     android:background="#00f" 
     /> 
</FrameLayout> 

sublayout.xml

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

</TextView> 

MainActivity

public class MainActivity extends Activity { 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

     LayoutInflater layoutInflater = getLayoutInflater(); 
     View view = layoutInflater.inflate(R.layout.sublayout, null); 
     FrameLayout frameLayout = (FrameLayout)findViewById(R.id.myframe); 
     setContentView(R.layout.activity_main); 
     frameLayout.addView(view); 
    } 


} 

我得到了錯誤爲「資源在收購附加的堆棧跟蹤,但從未發佈。有關避免資源泄漏的信息,請參見java.io.Closeable。 j ava.lang.Throwable:顯式的終止方法「關閉」不叫」

+0

您可以發佈全堆棧跟蹤 – Vishwa

+0

的FrameLayout frameLayout =(FrameLayout)findViewById(R.id.myframe); setContentView(R.layout.activity_main)在設置視圖內容之前找到了? – codebased

+0

你膨脹的目的是什麼? – Keshav1234

回答

0

問題是你嘗試設置的內容視圖嘗試在此之前訪問視圖..

@Override 
protected void onCreate(Bundle savedInstanceState) { 
super.onCreate(savedInstanceState); 
setContentView(R.layout.activity_main); 
FrameLayout frameLayout = (FrameLayout)findViewById(R.id.myframe); 
LayoutInflater layoutInflater = getLayoutInflater(); 
View view = layoutInflater.inflate(R.layout.sublayout, null); 
frameLayout.addView(view); 
} 
+0

已將setcontentView()放在最後。但仍然是相同的錯誤 –

+0

@BrightVarghese把setContentView放在下面的oncreate方法(即下面super.onCreate(savedInstanceState); – Vishwa

+0

是否必須在代碼中添加setContentView()?我也試過沒有這個方法,但同樣的錯誤 –