1. 程式人生 > >自定義View通過findviewbyid返回為null解決方法

自定義View通過findviewbyid返回為null解決方法

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>