Add button to a layout programmatically
Posted
by
mmmbaileys
on Stack Overflow
See other posts from Stack Overflow
or by mmmbaileys
Published on 2011-02-05T15:13:22Z
Indexed on
2012/12/15
23:04 UTC
Read the original article
Hit count: 158
I'm having trouble adding a button to a layout that I've created in XML. Here's what I want to achieve:
//some class
else {
startActivity(new Intent(StatisticsScreen.this, ScreenTemperature.class));
}
////
//ScreenTemperatureClass
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//this is where I call another class that
//displays a nice graph
setContentView(new GraphTemperature(getApplicationContext()));
}
I want to add a Button
to this new screen so that it'll appear below the graph.
I've tried creating a LinearLayout
view, then create a Button
and add it to this view but I just get NullPointerException
s..
Any help would be appreciated. Thanks
EDIT#1
Here's what I've tried using that created a NullPointerException
and 'force close':
Button buybutton;
LinearLayout layout;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new GraphTemperature(getApplicationContext()));
layout = (LinearLayout) findViewById(R.id.statsviewlayout);
Button buyButton = new Button(this);
buyButton.setText(R.string.button_back);
buyButton.setLayoutParams(new LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
layout.addView(buyButton);
}
And here's the logcat error:
ERROR/AndroidRuntime(293): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.weatherapp/com.weatherapp.ScreenTemperature}: java.lang.NullPointerException
ERROR/AndroidRuntime(293): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
ERROR/AndroidRuntime(293): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
ERROR/AndroidRuntime(293): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
ERROR/AndroidRuntime(293): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
theres abviously more lines to do with this error in logcat, not sure if you want it?
EDIT#2
So i tried bhups method:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GraphTemperature GT = new GraphTemperature(getApplicationContext());
layout = (LinearLayout) findViewById(R.id.statsviewlayout);
Button buyButton = new Button(this);
buyButton.setText(R.string.button_back);
buyButton.setLayoutParams(new LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
layout.addView(GT); // line 27
layout.addView(buyButton);
setContentView(layout);
}
This method produced the same logcat error as above, NullPointerException
, indicating it was something to do with line no. 27 which is the layout.addView
line of code. Any ideas? Thanks again
© Stack Overflow or respective owner