我無法將按鈕添加到我在XML中創建的佈局中。這是我想達到的目標:以編程方式將按鈕添加到佈局
//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()));
}
我想一個Button
到這個新的屏幕,以便它會顯示在圖形下方。 我試圖創建一個LinearLayout
視圖,然後創建一個Button
並將其添加到這個看法,但我只是得到NullPointerException
秒。
任何幫助,將不勝感激。由於
編輯#1
這裏就是我使用創建一個NullPointerException
和 '強制關閉' 的嘗試:
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);
}
而這裏的logcat的錯誤:
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)
在logcat中顯然有更多的線路處理這個錯誤,不確定是否需要它?
EDIT#2
所以我嘗試bhups方法:
@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);
}
此方法生產的相同的logcat錯誤如上,NullPointerException
,表明它是是與線沒有。 27這是layout.addView
代碼行。有任何想法嗎?再次感謝
讓我們瞭解您嘗試與logcat的你得到運行,所以我們試圖找出爲什麼你NPE反正考慮創建一個`screen_temperature.xml`佈局和使用,在`的setContentView()`。你可以通過指定整個包來添加xml自定義視圖,而不僅僅是名稱(即:` `) –
bigstones
2011-02-05 15:29:16
創建線性佈局(ll)並添加GraphTemp視圖對象和按鈕對象爲ll。然後將活動的內容視圖設置爲ll。即setContentView(ll); – bhups 2011-02-05 15:39:23