版权声明:转载请注明出处。作者:两仪织,博客地址:http://blog.csdn.net/u013894427 https://blog.csdn.net/u013894427/article/details/84324115
findviewbyid 返回为null,这个问题一般说明想要找的view没有在对应的layout上面。
今天遇到一个同样的问题,但是确定view已经在layout上,但是仍然返回为null。虽然最终找到了问题原因,但是过程艰辛。
具体代码如下
MainActivity.java
public class MainActivity extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
CustomFragment.java
public class CustomFragment extends Fragment
{
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState)
{
View view=inflater.inflate(R.layout.my_fragment,container,false);
CustomLayout custom1=view.findViewById(R.id.custom1);
custom1.setVisibility(View.GONE);
return view;
}
}
原因是在自定义View的时候自动生成了一个只有一个带context的构造函数,手动添加第二个构造函数之后,没有把super里面的第二个参数加上。
解决方法很简单,就是把下面的super(context)修改为super(context,attrs)
CustomLayout.java
public class CustomLayout extends LinearLayout
{
public CustomLayout(Context context, AttributeSet attrs)
{
super(context);
View view=LayoutInflater.from(context).inflate(R.layout.custom_layout,this);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<fragment
android:id="@+id/customFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="com.xxx.validatedemo.CustomFragment">
</fragment>
</android.support.constraint.ConstraintLayout>
custom_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent">
<TextView
android:text="hello"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:text="world"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
my_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.xxx.validatedemo.CustomLayout
android:id="@+id/custom1"
android:layout_height="wrap_content"
android:layout_width="wrap_content">
</com.xxx.validatedemo.CustomLayout>
</LinearLayout>