我是Android新手,我正在尝试在我的视图中添加一个简单的按钮,但我的观点完全是空白的。这是我的设置:
编辑:我现在已经改变了我的代码以编程方式编写,因为我已经习惯了iOS。
我现在收到以下错误:
错误:尝试在空对象引用上调用虚方法'void android.widget.LinearLayout.setOrientation(int)'
activity_main.xml中
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/linearLayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</LinearLayout>
MainActivity.java
public class MainActivity extends Activity {
LinearLayout linearLayout;
public Button myButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
// Create main view
linearLayout = (LinearLayout) findViewById(R.id.linearLayout1);
linearLayout.setOrientation(LinearLayout.VERTICAL);
// Create button
myButton = new Button(this);
myButton.setText("Fire Call");
// Add button to view
linearLayout.addView(myButton);
}
}
答案 0 :(得分:0)
我无法查明错误,但也许你可以。 在您输入的每一行之后尝试检查并查看该按钮是否出现。还要检查问题是仅使用按钮还是扩展到其他布局。
不要忘记在每一步之后保存。通常所有这些问题都可以通过详细的调试来解决。 如果没有出现布局,请尝试重新启动软件。
答案 1 :(得分:0)
你没有打电话给setContentView(R.layout.activity_main)
,在你的代码中,你评论了它,所以你的布局没有膨胀,所以你有一个空白的白色屏幕。取消注释该行,你会没事的。
答案 2 :(得分:0)
您需要setContentView
获取视图或布局资源ID。
此外,如果您提供布局资源ID,则只能调用findViewById
,并使用它调用setContentView
。或者,您可以对其进行充气并在生成的膨胀视图上调用view.findViewById
。
以下是您的代码,其中包含一些可能有助于修复新问题的更改:
public class MainActivity extends Activity {
LinearLayout linearLayout;
public Button myButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
// Create main view
linearLayout = new LinearLayout(this);
linearLayout.setOrientation(LinearLayout.VERTICAL);
// Create button
myButton = new Button(this);
myButton.setText("Fire Call");
// Add button to view
linearLayout.addView(myButton);
setContentView(linearLayout);
}
}