簡體   English   中英

使用自定義視圖時,findViewById崩潰 <merge> 和 <include> 標簽

[英]findViewById crashing when using a custom view with <merge> and <include> tags

我正在嘗試使用XML創建自定義視圖,然后檢索其屬性並進行編輯。 此自定義視圖多次添加到test2視圖中,每個視圖都有不同的ID。 我嘗試檢索其中一個自定義視圖(player_1)的ID,然后獲取TextView(player_name),並編輯其屬性,並且沒有其他視圖(例如player_2 id視圖)。

但是我不確定這是否可能? 它可以正常顯示,但是每次嘗試在代碼中執行此操作時都會出錯。 我真的不確定如何解決這個問題,相反,我似乎也無法進行測試。 有任何想法嗎?

謝謝!

Game.java

setContentView(R.layout.test2);

View player1 = (View) findViewById(R.id.player_1);

TextView player1Name = (TextView) player1.findViewById(R.id.player_name);

player1Name.setText("John");

test2.xml

<include
    layout="@layout/player_view"
    android:id="@+id/player_1"
/>
<include
    layout="@layout/player_view"
    android:id="@+id/player_2"
/>

player_view.xml

<?xml version="1.0" encoding="utf-8"?>
<merge
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:player="http://schemas.android.com/apk/res/com.example.android.merge">
<LinearLayout
android:id="@+id/top_view"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
>
        <TextView
        android:id="@+id/player_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView"
        >
        </TextView>
   </LinearLayout>
</merge>

這是player_view.xml的簡化版本,如有需要,我可以發布更多內容。

另外我還沒有弄清楚它是否甚至在eclipse中打印了錯誤消息,它進入了調試模式,並且沒有進一步說明問題是什么。

您的player_view.xml具有未知類型,因此include混淆了它是哪種View。 嘗試執行下一個操作:使用或創建可與player_view.xml合並的新PlayerView類。

將test2.xml編輯為:

<PlayerView
    android:id="@+id/player_1"
/>
<PlayerView
    android:id="@+id/player_2"
/>

然后在您的代碼中將其充氣如下:

setContentView(R.layout.test2);

PlayerView player1 = (PlayerView) findViewById(R.id.player_1);
LayoutInflater inflate = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflate.inflate(R.layout.player_view, player1);

對player2做同樣的事情。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM