[英]Android findViewById() returns null
我知道有很多與我類似的問題,但沒有一個給我答案。
我有一個布局:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:id="@+id/layout_main">
<HorizontalScrollView
android:id="@+id/scroll">
<LinearLayout
android:id="@+id/linear">
</LinearLayout>
</HorizontalScrollView>
</RelativeLayout>
當在 Activity 的 onCreate 中發生以下情況時:
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
layoutMain = (RelativeLayout) findViewById(R.id.layout_main);
linearLayout = (LinearLayout) findViewById(R.id.linear);
scrollView = (HorizontalScrollView) findViewById(R.id.scroll);
linearLayout 和 scrollView 都包含我需要的視圖,但 layoutMain 為空。 這怎么會發生,我如何獲得findViewById(R.id.layout_main)
?
如果您使用 Android Studio 等待 gradle 完成構建項目,這可能會解決問題。 也嘗試重新啟動 Android Studio。
你沒有 layout_height。 將其設置在 match_patent 上。
您的 xml 布局缺少重要屬性。 為視圖提供android:layout_height
和android:layout_width
。 看下面的xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/layout_main">
<HorizontalScrollView
android:id="@+id/scroll"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:id="@+id/linear"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
</LinearLayout>
</HorizontalScrollView>
</RelativeLayout>
更新
正如您在評論中所說,寬度/高度屬性存在於實際代碼中。 然后我建議刪除項目模塊下構建文件夾的子目錄並重建項目
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.