我一直在尝试在android-studio的滚动视图内向线性布局添加相对布局。
它一直给我一个错误:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.LinearLayout.addView(android.view.View)' on a null object reference
我认为可能由于太多的布局而无法将其添加到滚动视图中。因此,我删除了所有内容并创建了一个小代码,如下所示:
public class ChildAccountsActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.child_accounts_activity);
LinearLayout linearLayout = findViewById(R.id.accountHolder);
Button myButton = new Button(this);
myButton.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT));
linearLayout.addView(myButton); <<--ERROR HERE
}
在这里,我只是想向线性布局添加一个按钮,但是它一直给我上述错误。
任何指导将不胜感激,请记住,我是编程的新手,很可能不知道自己在做什么。谢谢您的时间:D
答案 0 :(得分:0)
代替此
Button myButton = new Button(this);
尝试
Button myButton = (Button) findViewById(R.id.HERE_YOUR_VIEW_ID);
答案 1 :(得分:0)
我为不同的屏幕尺寸创建了多个布局,并且在引用时产生了问题。我通过删除所有多余的布局来修复它,但是可能有更好的方法来解决此问题。