![](/img/trans.png)
[英]How can I change the width of a RelativeLayout that has a GridLayout as child?
[英]How can i change visible relativelayout on android?
试图找到解决方案,当我尝试这样做时,程序以某种方式崩溃了。
我的代码有什么问题,找不到执行此操作的任何原因?
无论如何,在程序的其他部分,类似的工作是否正确?
一点点代码来解释我的问题..
my.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中定义的,您可以直接在它们上调用findViewById。
在onCreate()
调用setContentView()
并使用findViewById()
查找。 否则,您将获得NullPointerException
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
switch();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.