当前位置: 代码迷 >> Android >> 自定义的控件,在用findViewById获取id是获取的到时null,为什么啊解决思路
  详细解决方案

自定义的控件,在用findViewById获取id是获取的到时null,为什么啊解决思路

热度:13   发布时间:2016-05-01 14:49:56.0
自定义的控件,在用findViewById获取id是获取的到时null,为什么啊?
控件:
public class LyricView extends TextView {
  public LyricView(Context context) {
super(context);
// TODO Auto-generated constructor stub
}

public LyricView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
}

public LyricView(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}
}
  xml:
<com.sample.andorid.LyricView android:name = "@+id/lyric_show" 
android:layout_width="fill_parent"
android:layout_height="220dip">
</com.sample.android.LyricView>

Activity 中引用:
在onCreat()函数中:
mLyricView =(LyricView)findViewById(R.id.lyric_show);
System.out.println("<-------The mLyricView is ------->" + mLyricView);
mLyricView.setText("hello world");
执行到这句是报错,打印出来是null.我大概知道LyricView要实例化,但是我不知道如何实例化!求高手指点,谢谢!

------解决方案--------------------
<com.sample.andorid.LyricView android:name = "@+id/lyric_show"
android:layout_width="fill_parent"
 android:layout_height="220dip">
 </com.sample.android.LyricView>

改为

<com.sample.andorid.LyricView android:id = "@+id/lyric_show"
android:layout_width="fill_parent"
 android:layout_height="220dip">
 </com.sample.android.LyricView>
  相关解决方案