试图找到解决方案,但当我尝试这样做时,程序以某种方式崩溃了。
我的代码有什么问题,找不到这样做的任何原因?
无论如何,在程序的其他部分非常相似的工作正常吗?
一些代码来解释我的问题..
我的.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
switch();
}
public void switch() {
RelativeLayout chatsLayout = (RelativeLayout)findViewById(R.id.chatsLayout);
RelativeLayout chats = (RelativeLayout) chatsLayout.findViewById(R.id.chats);
chats.setVisibility(View.GONE);
RelativeLayout noChats = (RelativeLayout) chatsLayout.findViewById(R.id.noChats);
noChats.setVisibility(View.GONE);
}
my.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/chatsLayout"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/white">
<RelativeLayout
android:id="@+id/chats"
android:visibility="gone"
android:padding="8dp"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
</RelativeLayout>
<RelativeLayout
android:id="@+id/noChats"
android:padding="8dp"
android:visibility="visible"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
</RelativeLayout>
</RelativeLayout>
这是我从 logcat 得到的错误代码:
08-10 08:06:00.922 2736-2736/fi.hgs.apps E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: fi.hgs.apps, PID: 2736
java.lang.RuntimeException: Unable to start activity ComponentInfo{fi.hgs.apps/fi.hgs.apps.ChatsActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.widget.RelativeLayout.findViewById(int)' on a null object reference
还有这个
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.widget.RelativeLayout.findViewById(int)' on a null object reference
最佳答案
你的 onCreate 应该是这样的:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
switch();
}
你的 switch 方法应该是这样的:
public void switch() {
RelativeLayout chatsLayout = (RelativeLayout)findViewById(R.id.chatsLayout);
RelativeLayout chats = (RelativeLayout)findViewById(R.id.chats);
chats.setVisibility(View.GONE);
RelativeLayout noChats = (RelativeLayout)findViewById(R.id.noChats);
noChats.setVisibility(View.GONE);
}
因为你的所有观点; chatsLayout、chats 和 noChats 定义在同一个 xml 中,它在您的 Activity 中膨胀,您可以直接调用它们的 findViewById。
关于java - 如何更改 android 上可见的相对布局?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31912163/