2013-01-11 22 views
1

有許多像這樣的問題,但解決方案對我而言並不奏效。FindViewByID(...)在設置內容視圖和清理項目後返回null

無論如何,我的主要活動有一個按鈕,它的onclick方法將我帶到另一個活動ViewPowerActivity。我有一個名爲power_view.xml的佈局xml文件。裏面,我有一些佈局:

<?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:layout_marginLeft="@dimen/screen_margin" 
android:layout_marginRight="@dimen/screen_margin" 
android:layout_marginTop="@dimen/screen_margin" 
android:orientation="vertical" > 
... 

ViewPowerActivity具有基本onCreateMethod:

public class ViewPowerActivity extends Activity { 
    private final static Powers powers=new StubPowers(); 

    @Override 
public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.power_view); 

     Power power=powers.getPowers().get(0); 
     View powerView = findViewById(R.layout.power_view); 
     ... 
    } 
    ... 
} 

的findViewById調用上面返回null。

如果我刪除setContentView(...)之後的所有代碼並簡單地返回,那麼它顯示空白布局就好了。我已經設置了內容視圖,我已經清理了該項目,我嘗試將權力視圖設置爲主要活動,以及各種各樣的事情。它還能是什麼?

+0

這將是R.id.power_view。這是xml的一個視圖。不是xml –

+0

你究竟想完成什麼? – 323go

+0

比你需要得到像這樣查看powerView = findViewById(R.id.layout); – Pragnani

回答

1

從你的代碼中可以明顯看出,power_view是一個佈局,即。 XML。所以R.id.power_view是不正確的。

看來你想要訪問該佈局的父視圖。然後執行以下操作。

您必須將id設置爲父LinearLayout。

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/parentLinear" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:layout_marginLeft="@dimen/screen_margin" 
    android:layout_marginRight="@dimen/screen_margin" 
    android:layout_marginTop="@dimen/screen_margin" 
    android:orientation="vertical" > 
    ... 

然後,

 View powerView = findViewById(R.id.parentLinear); 

如果你想在PowerView的其他一些觀點,你應該設置ID以XML佈局視圖和初始化通過findViewById(R查看到power_view。 id.your_view)

+0

如果此答案可以幫助您,請接受並註冊。請讓我知道。 – Debarati

+0

這太棒了!我參考線性佈局本身,然後獲取文本視圖並填充信息。 SOme的其他錯誤已經出現,但這是朝正確方向邁出的一步。謝謝! – whiterook6

0
 power_view.xml 


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

    android:id="@+id/layout" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:layout_marginLeft="@dimen/screen_margin" 
    android:layout_marginRight="@dimen/screen_margin" 
    android:layout_marginTop="@dimen/screen_margin" 
    android:orientation="vertical" > 



    public class ViewPowerActivity extends Activity { 
     private final static Powers powers=new StubPowers(); 

     @Override 
    public void onCreate(Bundle savedInstanceState) { 
      super.onCreate(savedInstanceState); 
      setContentView(R.layout.power_view); 

      Power power=powers.getPowers().get(0); 
      View powerView = (ViewGroup)findViewById(R.id.layout); 
      ... 
     } 
     ... 
    }