开发者

Android findViewById Null Scope Issue

I am having a few problems with how I've structured my App. I have a click handler in my Core class that I decided I want to be forwarded to another class to make my code smaller and more modular, the problem is inside ButtonClass, findViewById always returns NULL, I believe due to being out of scope.

In my XML manifest file I do have: android:name="com.prj.MyAppName"

In my core class things work fine, but once I create a new class I cannot use findViewById() inside of it.

Here is a stripped down version of my code:

public class Class1 extends Core
{
    Button buttonHint1 = (Button)findViewById(R.id.buttonHint1);
}

public class Core extends Activity
{
    public void myClickHandler(View target)
    {
        //THIS WORKS
        //TextView userText2 = (TextView) findViewById(R.id.textViewHint1);
        //userText2.setText( "OKOKOKO" );

        ButtonClass myButtonClass = new ButtonClass();
        myButtonClass.myClickHandler(target);
    }
}

public class ButtonClass extends Core
{
    public void myClickHandler(View target)
    {
        switch( target.getId() )
        {
            case R.id.buttonHint1:
                //CRASHES ON findViewById ()!!!
                TextView userText1 = (TextView) findViewById(R.id.textViewHint1);
                userText1.setText( "OKOKOKO" );
            break;
        }
    }
}
开发者_如何学Python

Does anyone know if there are any modifications I can make to allow ButtonClass to be able to use findViewById and perhaps fix my scoping issues so my App does not crash?

I am still learning Android and would appreciate any advice.


Why not change the constructor of ButtonClass to allow the parameter (TextView)findViewById(R.id.textViewHint1)?

public ButtonClass(TextView tv){
//constructor stuff
}

If this is called in an Activity it should work.

Edit: My mistake, not TextView, Button!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜