Reputation: 97
I am reading a book on building an app called "Dot Smasher."
I decide to approach one of the task by adding a button above canvas. I decide to use LinearLayout and did the following:
public class MainActivity extends AppCompatActivity {
private Timer timer;
private DotSmasherCanvas canvas;
private DotSmasherTimerTask task;
private Button button;
private LinearLayout layout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle("DotSmasher");
canvas = new DotSmasherCanvas(getBaseContext());
timer = new Timer();
task = new DotSmasherTimerTask(canvas);
timer.schedule(task, 0, 1500);
button = (Button) findViewById (R.id.button);
layout = (LinearLayout) findViewById(R.id.layout);
layout.addView(canvas);
setContentView(R.layout.activity_main);
}
}
This is the xml file -- activity_main.xml:
I am able to get it work if I only did setContentView(canvas);
But not above, what did I do wrong?
There's no error display in Android Studio until I try to run it.
Upvotes: 0
Views: 513
Reputation: 93614
You don't seem to understand how layouts work. You're calling findViewById before calling setContentView. That won't work- until you set a content view, there's no place to search for a view. And you shouldn't mix xml layouts and programmatic views unless you have a very dynamic layout- either your DotSmasherCanvas should be in the layout, or none of it should be in xml (probably the first).
Upvotes: 1