簡體   English   中英

findViewById在自定義視圖中返回null

[英]findViewById returns null in custom view

好的,我已經讀過一個自定義視圖必須具有帶有AttributeSet的構造函數,以便findViewById()起作用。 我還沒有看到任何實際的實現。

下面是我的代碼:擴展了Horizo​​ntalScrollView的自定義視圖:

public AnimatedMenuBar(Context context) {
        // TODO Auto-generated constructor stub
        this(context, null);
    }

    public AnimatedMenuBar(Context context, AttributeSet attrs) {
        // TODO Auto-generated constructor stub
        this(context, attrs, 0);
    }

    public AnimatedMenuBar(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        // TODO Auto-generated constructor stub
        this.context = context;
        inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        inflater.inflate(R.layout.main, this);
        this.setHorizontalScrollBarEnabled(false);
    }

從我的主要活動中:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.testing);
        AnimatedMenuBar animatedMenuBar = (AnimatedMenuBar)findViewById(R.id.animatedMenuBar);
}

testing.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="match_parent">
    <com.pt.task.custommenubar.AnimatedMenuBar
        android:id="@+id/animatedMenuBar" android:layout_width="fill_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

main.xml中

<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent" android:layout_height="wrap_content" >
    <LinearLayout android:id="@+id/horizontalLayout" android:orientation="horizontal"
        android:layout_width="fill_parent" android:layout_height="wrap_content">
        <TextView android:layout_width="wrap_content"
            android:layout_height="wrap_content" android:id="@+id/dummyTextView" android:padding="5dip"/>
    </LinearLayout>
</merge>

animationMenuBar始終為null,有什么我想念的嗎?

非常感謝你!

我遇到了這樣的錯誤。

  1. 嘗試Project-clean。 有時會有所幫助。
  2. 如果AnimatedMenuBar支持自定義菜單,則編寫com.pt.task.custommenubar $ AnimatedMenuBar
  3. 嘗試在代碼中的所有位置重命名AnimatedMenuBar。

順便說一句,這可能不適合在這里問,您能否向我解釋一下如何在構造函數內部簡單地調用inflate()而不繪制任何內容的情況下繪制視圖。 –然后阿爾文

當您調用此inflater.inflate(R.layout.main, this) ,充氣器將充氣main.xml並將充氣后的View放入自定義視圖的ViewGroup中。

與Activity中的setContentView(R.layout.main)具有相同的效果

暫無
暫無

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

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