Search code examples
androidandroid-preferenceslive-wallpaper

findViewById() returns null


There are a few questions already asking about this, but I'm not finding a solution. I have a LiveWallpaper that is using its own subclass of PreferenceFragment to specify preferences. The solution most often cited is to assure that setContentView() is called before findViewByID(). I am not calling setContentView() at all because I do not have a layout specified. This app originally implemented the preferences using the deprecated methods like PreferenceActivity.getPreferenceManager() and without using a layout and worked just fine. I am trying to bring the code up-to-date in using PreferenceFragment.
Am I required to have a layout and if so, what would I have when I don't really want one?
Or is there a another way to get/set the View?

public class SetPreferenceActivity extends Activity {    
    private CheckBox redCheckBox;    

@Override  
protected void onCreate(Bundle savedInstanceState) {  
    super.onCreate(savedInstanceState);  
    //setContentView(R.layout.main);  ???
    redCheckBox = (CheckBox)findViewById(R.id.redCheckBox);  // returns null
    getFragmentManager().beginTransaction().replace(android.R.id.content, new LiveWallpaperPreferenceFragment()).commit();  
    }  
}  

Solution

  • You can create views dynamically :

    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
    
        TextView textView = new TextView(this);
        textView.setText("Hello");
    
        setContentView(textView);//<----set the view !
    
        }  
    }