如何在片段中设置绑定?

How to set binding in a Fragment?

我正在尝试在我的应用程序中构建一个“记笔记”区域。我在视图绑定方面遇到了问题。我按照这个代码示例“https://codingwithsaud.medium.com/how-to-make-note-app-in-android-studio-part-1-443ccf16921e”进行了 T,但它主要构建在 activity 而不是片段中。我目前正在片段中构建它,除了我的“Equipment_Tracker.kt”之外,其他一切都很好,我不知道出了什么问题。列表问题发生在“Equipment_Tracker.kt” 在此先感谢您的帮助。

列出弹出的错误。

Unresolved reference: setContentView
Smart cast to 'FragmentEquipmentTrackerBinding' is impossible, because 'binding' is a mutable property that could have been changed by this time

Type mismatch: inferred type is Equipment_Tracker but Context? was expected

Smart cast to 'FragmentEquipmentTrackerBinding' is impossible, because 'binding' is a mutable property that could have been changed by this time

None of the following functions can be called with the arguments supplied:
public constructor Intent(p0: Context!, p1: Class<*>!) defined in android.content.Intent
public constructor Intent(p0: String!, p1: Uri!) defined in android.content.Intent

Smart cast to 'FragmentEquipmentTrackerBinding' is impossible, because 'binding' is a mutable property that could have been changed by this time
Smart cast to 'FragmentEquipmentTrackerBinding' is impossible, because 'binding' is a mutable property that could have been changed by this time
Smart cast to 'FragmentEquipmentTrackerBinding' is impossible, because 'binding' is a mutable property that could have been changed by this time
Smart cast to 'FragmentEquipmentTrackerBinding' is impossible, because 'binding' is a mutable property that could have been changed by this time
Smart cast to 'FragmentEquipmentTrackerBinding' is impossible, because 'binding' is a mutable property that could have been changed by this time
Smart cast to 'FragmentEquipmentTrackerBinding' is impossible, because 'binding' is a mutable property that could have been changed by this time
Smart cast to 'FragmentEquipmentTrackerBinding' is impossible, because 'binding' is a mutable property that could have been changed by this time
Smart cast to 'FragmentEquipmentTrackerBinding' is impossible, because 'binding' is a mutable property that could have been changed by this time
Smart cast to 'FragmentEquipmentTrackerBinding' is impossible, because 'binding' is a mutable property that could have been changed by this time
Smart cast to 'FragmentEquipmentTrackerBinding' is impossible, because 'binding' is a mutable property that could have been changed by this time
Smart cast to 'FragmentEquipmentTrackerBinding' is impossible, because 'binding' is a mutable property that could have been changed by this time
None of the following functions can be called with the arguments supplied:
public open fun makeText(p0: Context!, p1: CharSequence!, p2: Int): Toast! defined in android.widget.Toast
public open fun makeText(p0: Context!, p1: Int, p2: Int): Toast! defined in android.widget.Toast
None of the following functions can be called with the arguments supplied:
public open fun makeText(p0: Context!, p1: CharSequence!, p2: Int): Toast! defined in android.widget.Toast
public open fun makeText(p0: Context!, p1: Int, p2: Int): Toast! defined in android.widget.Toast

Equipment_Tracker.kt

package com.example.armymaintenance

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import com.example.armymaintenance.Model.note_model
import com.example.armymaintenance.database.MySqliteHelper
import com.example.armymaintenance.databinding.FragmentEquipmentTrackerBinding

class Equipment_Tracker : Fragment() {
    

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_equipment__tracker, container, false)

    }

    var binding: FragmentEquipmentTrackerBinding? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = FragmentEquipmentTrackerBinding.inflate(layoutInflater)
        setContentView(binding.getRoot())
        val helper = MySqliteHelper(this)
        binding.btnDisplay.setOnClickListener(View.OnClickListener {
            val intent = Intent(this@Equipment_Tracker, Equipment_Tracker::class.java)
            startActivity(intent)
        })
        binding.btnSave.setOnClickListener(View.OnClickListener {
            val model = note_model()
            model.bumpernumber = binding.bumpernumber.text.toString()
            model.description = binding.description.text.toString()
            model.nsn = binding.nsn.text.toString()
            model.serialnumber = binding.serialnumber.text.toString()
            model.date = binding.date.text.toString()
            if (model.bumpernumber.isEmpty()) {
                binding.bumpernumber.error = "Enter bumper number"
                return@OnClickListener
            }
            if (model.description.isEmpty()) {
                binding.description.error = "Enter description"
                return@OnClickListener
            }
            if (model.nsn.isEmpty()) {
                binding.nsn.error = "Enter nsn"
                return@OnClickListener
            }
            if (model.serialnumber.isEmpty()) {
                binding.serialnumber.error = "Enter serial number"
                return@OnClickListener
            }
            if (model.date.isEmpty()) {
                binding.date.error = "Enter date"
                return@OnClickListener
            }
            val r = helper.saveNote(model)
            if (r) {
                Toast.makeText(this@Equipment_Tracker, "note is saved", Toast.LENGTH_SHORT).show()
            } else {
                Toast.makeText(this@Equipment_Tracker, "some thing want wrong", Toast.LENGTH_SHORT)
                    .show()
            }
        })
    }

}

fragment_equipment_tracker.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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=".Equipment_Tracker">

    <LinearLayout
        android:layout_centerInParent="true"
        android:padding="10dp"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <EditText
            android:id="@+id/bumpernumber"
            android:hint="Bumper Number"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
        <EditText
            android:id="@+id/description"
            android:hint="Enter description"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
        <EditText
            android:id="@+id/nsn"
            android:hint="Enter nsn"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
        <EditText
            android:id="@+id/serialnumber"
            android:hint="Enter serial number"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
        <EditText
            android:id="@+id/date"
            android:hint="Enter date"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
        <Button
            android:id="@+id/btnSave"
            android:text="Save"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
        <Button
            android:id="@+id/btnDisplay"
            android:text="Display"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
    </LinearLayout>

</RelativeLayout>

note_model.java

package com.example.armymaintenance.Model;

public class note_model {

    private int id;
    private String bumpernumber;
    private String description;
    private String nsn;
    private String serialnumber;
    private String date;

    public note_model() {
    }

    public note_model(int id, String bumpernumber, String description, String nsn, String serialnumber, String date) {
        this.id = id;
        this.bumpernumber = bumpernumber;
        this.description = description;
        this.nsn = nsn;
        this.serialnumber = serialnumber;
        this.date = date;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getBumpernumber() {
        return bumpernumber;
    }

    public void setBumpernumber(String bumpernumber) {
        this.bumpernumber = bumpernumber;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }
    public String getNsn() {
        return nsn;
    }

    public void setNsn(String nsn) {
        this.nsn = nsn;
    }

    public String getSerialnumber() {
        return serialnumber;
    }

    public void setSerialnumber(String serialnumber) {
        this.serialnumber = serialnumber;
    }

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }
}

MySqliteHelper.java

package com.example.armymaintenance.database;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import androidx.annotation.Nullable;

import com.example.armymaintenance.Model.note_model;

import java.util.ArrayList;
import java.util.List;

public class MySqliteHelper extends SQLiteOpenHelper {
    private static final String DATABASE_NAME="note.db";
    private static final int VERSION=1;
    public MySqliteHelper(@Nullable Context context) {
        super(context, DATABASE_NAME, null, VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        String table1="create table "+TableSchema.note.TABLE_NAME+"("+TableSchema.note.ID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+TableSchema.note.BUMPERNUMBER+" TEXT, "+TableSchema.note.DESCRIPTION+" TEXT,"+TableSchema.note.NSN+" TEXT,"+TableSchema.note.SERIALNUMBER+" TEXT, "+TableSchema.note.DATE+" TEXT );";
        sqLiteDatabase.execSQL(table1);
    }

    public boolean saveNote(note_model model){
        SQLiteDatabase database=this.getWritableDatabase();
        ContentValues cv=new ContentValues();
        cv.put(TableSchema.note.BUMPERNUMBER,model.getBumpernumber());
        cv.put(TableSchema.note.DESCRIPTION,model.getDescription());
        cv.put(TableSchema.note.NSN,model.getNsn());
        cv.put(TableSchema.note.SERIALNUMBER,model.getSerialnumber());
        cv.put(TableSchema.note.DATE,model.getDate());
        long id= database.insert(TableSchema.note.TABLE_NAME,null,cv);
        if (id==-1){
            return false;
        }
        return true;
    }
    public List<note_model> getAllNotes(){
        SQLiteDatabase database= this.getReadableDatabase();
        String[] cols={TableSchema.note.ID,TableSchema.note.BUMPERNUMBER,TableSchema.note.DESCRIPTION,TableSchema.note.NSN,TableSchema.note.SERIALNUMBER,TableSchema.note.DATE};
        Cursor cursor=database.query(TableSchema.note.TABLE_NAME,cols,null,null,null,null,TableSchema.note.ID+" DESC");
        ArrayList<note_model> list=new ArrayList<>();
        while (cursor.moveToNext()){
            note_model model=new note_model();
            model.setId(cursor.getInt(cursor.getColumnIndex(TableSchema.note.ID)));
            model.setBumpernumber(cursor.getString(cursor.getColumnIndex(TableSchema.note.BUMPERNUMBER)));
            model.setDescription(cursor.getString(cursor.getColumnIndex(TableSchema.note.DESCRIPTION)));
            model.setNsn(cursor.getString(cursor.getColumnIndex(TableSchema.note.NSN)));
            model.setSerialnumber(cursor.getString(cursor.getColumnIndex(TableSchema.note.SERIALNUMBER)));
            model.setDate(cursor.getString(cursor.getColumnIndex(TableSchema.note.DATE)));
            list.add(model);
        }
        cursor.close();
        database.close();
        return list;
    }
    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
        if (i<i1){
            sqLiteDatabase.execSQL("DROP TABLE IF EXISTS "+TableSchema.note.TABLE_NAME);
        }

    }
}

TableSchema.java

package com.example.armymaintenance.database;

public class TableSchema {

    public static class note{

        public static final String TABLE_NAME="tbl_note";
        public static final String ID="id";
        public static final String BUMPERNUMBER="bumpernumber";
        public static final String DESCRIPTION="description";
        public static final String NSN="nsn";
        public static final String SERIALNUMBER="serialnumber";
        public static final String DATE="date";
    }

}

绑定错误请查看此文档查看绑定 https://developer.android.com/topic/libraries/view-binding#kts

在Activity中你可以初始化lateinit var binding: ActivityMainBinding 并且可以像这样膨胀视图

 binding = ActivityMainBinding.inflate(layoutInflater)
    val view = binding.root
    setContentView(view) 

但片段的方式不同

private var _binding: FragmentMainBinding? = null
private val binding get() = _binding!!

并且在 onCreateView 方法中你必须这样做

_binding = FragmentMainBinding.inflate(inflater, container, false)
    val view = binding.root
    return view

请确保您是在 onCreateView 而不是 onViewCreated

并且在 onDestroyView 中,您必须将其值设置为 null

override fun onDestroyView() {
    super.onDestroyView()
    _binding = null
}

这是进行绑定的正确方法您还可以访问文档以获取更多信息