2017-03-31 79 views
0

您好我已編碼以下從包含佈局獲取視圖。但我得到空指針異常。我錯在哪裏?如何引用視圖內包含佈局android

我的Java代碼:

View actionbar = findViewById(R.id.actionbar); 
       RelativeLayout actionRRl = (RelativeLayout)actionbar.findViewById(R.id.actionRR); 
       actionRRl.setEnabled(false); 
       actionRRl.setClickable(false); 

在我Activity.xml,

<include 
      android:id="@+id/actionbar" 
      layout="@layout/actionbar" /> 

佈局所包含,即actionbar.xml

<?xml version="1.0" encoding="utf-8"?> 
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:background="@drawable/header" 
     android:focusable="false" 
     android:focusableInTouchMode="false" 
     android:clickable="false" 
     android:id="@+id/actionRR" 
     android:orientation="vertical"> 

     <ImageView 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_alignParentLeft="true" 
      android:clickable="false" 
      android:padding="@dimen/logo_size" 
      android:src="@drawable/logo" /> 

    </RelativeLayout> 

錯誤堆棧:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setEnabled(boolean)' on a null object reference 

回答

1

給予ID到你的佈局包括象下面這樣:

<include android:id="@+id/actionbar" 

覆蓋您包含的佈局中的父ID。

在你的情況下,改變你的代碼,這樣就可以解決問題:

View actionbar = findViewById(R.id.actionbar); 
actionbar.setEnabled(false); 
actionbar.setClickable(false); 
0

一旦你包括工具欄佈局,以你的活動,其成分屬於你的活動爲好,這樣你就可以直接

RelativeLayout actionRRl = (RelativeLayout) findViewById(R.id.actionRR); 
actionRRl.setEnabled(false); 
actionRRl.setClickable(false); 
+0

想你的代碼:它投擲的錯誤隊友! 引起:java.lang.NullPointerException:嘗試調用null對象的虛擬方法'void android.widget.RelativeLayout.setEnabled(boolean)'引用 –

+0

請確保您在'setContentView() –

0

實例他們試試這個

RelativeLayout actionRRl = (RelativeLayout)findViewById(R.id.actionRR); 
       actionbar.setEnabled(false); 
       actionbar.setClickable(false); 

您也可以膨脹的佈局獲得一個視圖,像這樣做,

View actionbar = LayoutInflater.from(this).inflate(R.layout.actionbar, null, false); 
RelativeLayout actionRRl = (RelativeLayout)actionbar.findViewById(R.id.actionRR); 
       actionRRl.setEnabled(false); 
       actionRRl.setClickable(false); 
+0

嗨@Yordan,那麼這裏的actionbar是什麼? –

+0

您不需要actionBar,它是對佈局資源的引用而不是視圖。 – Yordan

相關問題