Question

Help! I am getting the findViewById null return value problem. I did tons of research and already clearned project, put setContentView ahead, but it still fail! The xml layout works fine because if i set my custom view's back ground to blue, the view will have blue color as expected when running the app. But i just cant use findViewById

layout 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>

custom view class, its parent class extends android's view class already:

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

}

}

Activity class:

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);

}
}
Was it helpful?

Solution

You are calling the wrong super constructor here:

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

Should be:

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

Also, in the pasted code for the activity I don't see the import for R, make sure you import your project's R file, and not com.android.R by mistake.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top