[Java] [Android Studio] View binding 完全淘汰 findViewById (Fragment篇)

 上一篇是Activity的ViewBinding

終於要來說Fragment了

一樣首先先打開build.gradle(Module:app),在android區塊裡面加入:

viewBinding {
enabled = true
}

記得點選右上角的Sync Now來匯入套件

建立Fragment,這裡叫MainFragment.java和fragment_main.xml

(Fragment建立可以看這篇:Navigation實作圖形化切換Fragment頁面(一))

因為是Fragment記得讓Fragment顯示在activity上面(如果是上一篇就要把「房子」放在MainFragment)

宣告物件:

(這裡的FragmentMainBinding是xml檔名用駝峰式命名加上Binding,所以如果你布局檔名和我不一樣記得更改)

FragmentMainBinding binding;

複寫onCreateViewonDestroyView方法(快速鍵Ctrl+O)

    @Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
// return super.onCreateView(inflater, container, savedInstanceState);
binding = FragmentMainBinding.inflate(inflater, container, false);
return binding.getRoot();
}

@Override
public void onDestroyView() {
super.onDestroyView();
binding = null;
}

上次一樣,一個TextView和Button來練習,只是是寫在fragment_main.xml

<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:text="Button"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView" />

回到MainFragment.java,複寫onViewCreated方法,在裡面寫入程式碼

binding.textView.setText("Hi");
binding.button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String s = (String) binding.textView.getText();
binding.textView.setText(s += "Hi");
}
});

成功!

留言