【发布时间】:2012-05-30 07:53:08
【问题描述】:
帮助!我遇到了 findViewById 空返回值问题。我做了大量的研究并已经清除了项目,将 setContentView 放在前面,但它仍然失败! xml 布局工作正常,因为如果我将自定义视图的背景设置为蓝色,则在运行应用程序时视图将具有预期的蓝色。但我就是不能使用 findViewById
布局 xml:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<shaotian.android.blackboard.BBView
android:id="@+id/bBView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</FrameLayout>
自定义视图类,其父类已经扩展了android的视图类:
package shaotian.android.blackboard;
import java.util.Observable;
import java.util.Observer;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class BBView extends shaotian.android.blackboard.View {
public BBView(Context context) {
super(context);
// TODO Auto-generated constructor stub
TextView txt=new TextView(context);
this.setBackgroundColor(Color.BLUE);
}
public BBView(Context context, AttributeSet attr)
{super(context);
this.setBackgroundColor(Color.BLUE);
}
public BBView(Context context,AttributeSet attr,int sty)
{
super(context,attr,sty);
this.setBackgroundColor(Color.BLUE);
}
@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
}
public void update(Observable arg0, Object arg1) {
// TODO Auto-generated method stub
}
}
活动类:
package shaotian.android.blackboard;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class BlackBoardActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
BBView view=(BBView)findViewById(R.id.bBView1);
}
}
【问题讨论】:
-
发布这个类 shaotian.android.blackboard.View ...
-
如果你的布局文件真的被称为
layout.xml,你应该考虑调用setContentView(R.layout.layout);而不是setContentView(R.layout.main);。 -
setContentView(R.layout.layout);
标签: android findviewbyid