【问题标题】:Android findViewById gets null. Already tried cleaning project, setcontentview firstAndroid findViewById 为空。已经尝试清理项目,先setcontentview
【发布时间】: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


【解决方案1】:

你在这里调用了错误的超级构造函数:

public BBView(Context context, AttributeSet attr)
{
   super(context);
   this.setBackgroundColor(Color.BLUE);
}

应该是:

public BBView(Context context, AttributeSet attr)
{
   super(context, attr);
   this.setBackgroundColor(Color.BLUE);
}

另外,在粘贴的活动代码中,我没有看到 R 的导入,请确保您导入了项目的 R 文件,而不是错误地导入了 com.android.R。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-27
    • 1970-01-01
    • 2013-07-15
    • 2013-06-28
    • 1970-01-01
    相关资源
    最近更新 更多