android fragment_main.xml 注意問題

新的安卓版本中建立工程時候layout 中會生成兩個xml文件一個activity_main.xml還有一個fragment_main.xml。

問題一:這兩個XML之間的關係

可以看一下activity_main.xml就明白

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.wapstore.Wap"
    tools:ignore="MergeRootFrame" />

可以看出一個activity中是可以包含多個fragment的

詳細瞭解可以看這裏 http://blog.csdn.net/guolin_blog/article/details/8881711

問題二:但是這裏會存在一個問題,比如在fragment_main.xml中定義了一個button,在activity中使用按鍵監聽就會出現空指針問題,導致程序閃退

解決辦法

方法一:activity.java中使用findviewbyid時候做一點改變

play = (Button) rootView.findViewById(R.id.play);

方法二:


1.刪除fragment_main.xml整個文件
2.對activity_main.xml,刪除裏面的內容。然後切換到Graphy Layout,放入一個LinearLayout就可以
3.對MainActivity.java,可以刪除部分的內容,再把MainActivity extends ActionBarActivity 改爲MainActivity extends Activity :

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
   
  
   
    <WebView
     android:id="@+id/webview"
     android:layout_width="match_parent"
     android:layout_height="match_parent" />
    
</LinearLayout>


這樣就可以隨意使用控件了


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章