繁体   English   中英

如何使用 Kotlin 片段内的按钮进行 android 开发?

[英]How do I use buttons inside fragments in Kotlin for android development?

我是 android 开发的新手,并从 android 工作室创建了一个新项目,在 Kotlin 中进行了底部导航活动。 除了MainActivity.kt还生成了仪表板、主页和通知片段及其 ViewModel。 当我处理 MainActivity class 内的按钮单击时,一切正常。

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val navView: BottomNavigationView = findViewById(R.id.nav_view)

        val navController = findNavController(R.id.nav_host_fragment)
        // Passing each menu ID as a set of Ids because each
        // menu should be considered as top level destinations.
        val appBarConfiguration = AppBarConfiguration(setOf(
                R.id.navigation_home, R.id.navigation_dashboard, R.id.navigation_notifications))
        setupActionBarWithNavController(navController, appBarConfiguration)
        navView.setupWithNavController(navController)

        //handle button click
        val temporary_button = findViewById<Button>(R.id.temporary_button)
        temporary_button.setOnClickListener{
            makeText(this, "You clicked the button", LENGTH_LONG).show()
        }
    }
}

这是一个工作按钮的屏幕截图按钮工作正常

但是我不明白如何使用不同片段中的按钮。 我试图在仪表板片段中为第二个按钮创建一个功能 第二个按钮的屏幕截图,但我没有找到解决方案。 我努力了

class DashboardFragment : Fragment() {

    private lateinit var dashboardViewModel: DashboardViewModel

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        dashboardViewModel =
            ViewModelProviders.of(this).get(DashboardViewModel::class.java)
        val root = inflater.inflate(R.layout.fragment_dashboard, container, false)
        val textView: TextView = root.findViewById(R.id.text_dashboard)
        dashboardViewModel.text.observe(this, Observer {
            textView.text = it
        })
        //handle button click
        val temporary_button = findViewById<Button>(R.id.temporary_button2)
        temporary_button2.setOnClickListener{
            makeText(this, "You clicked the button", LENGTH_LONG).show()
        }
        return root
    }

}

但显然这段代码

//handle button click
    val temporary_button = findViewById<Button>(R.id.temporary_button2)
    temporary_button2.setOnClickListener{
        makeText(this, "You clicked the button", LENGTH_LONG).show()
    }

是错的。 Another thing that I have tried is changing the fragment_dashboard.xml file and setting the onClick property to a function name ( android:onClick="button2click" ). 这是整个 xml:

    <androidx.constraintlayout.widget.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" >

    <TextView
        android:id="@+id/text_dashboard"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:textAlignment="center"
        android:textSize="20sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>

    <Button
        android:id="@+id/temporary_button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="192dp"
        android:layout_marginBottom="248dp"
        android:onClick="button2click"
        android:text="Button2"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintStart_toStartOf="parent" />

我尝试像这样使用 function:

class DashboardFragment : Fragment() {

    private lateinit var dashboardViewModel: DashboardViewModel

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        dashboardViewModel =
            ViewModelProviders.of(this).get(DashboardViewModel::class.java)
        val root = inflater.inflate(R.layout.fragment_dashboard, container, false)
        val textView: TextView = root.findViewById(R.id.text_dashboard)
        dashboardViewModel.text.observe(this, Observer {
            textView.text = it
        })

        return root
    }
    fun button2click (view: View){
        println("Button clicked")
    }

}

但这样它不起作用,当我单击按钮时应用程序崩溃。

任何有关如何使用片段内按钮的帮助都会受到赞赏。

使用 getView()/view 尝试你的内部 onViewCreated 而不是 onCreateView。

例如:

override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
   val temporary_button = getView().findViewById<Button>(R.id.temporary_button2)
   temporary_button2.setOnClickListener{
   makeText(this, "You clicked the button", LENGTH_LONG).show()
   }
 }

片段中没有findViewById ,通常在片段中您应该覆盖onCreateView方法,膨胀您自己的布局并尝试从您膨胀的视图中获取视图。 例如:

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (mContentView == null){
            mContentView = inflater.inflate(R.layout.family_fragment_scene_list, container, false);
        }

        type = getArguments().getInt(ARGS_KEY_TYPE);

        adapter = new SceneAdapter(getContext());
        // get views from mContentView
        mSceneList = (RecyclerView) mContentView.findViewById(R.id.swipe_target);
        mSceneList.setLayoutManager(new LinearLayoutManager(getContext()));
        mSceneList.setAdapter(adapter);

        return mContentView;
    }

这就是我最终得到的结果:

class DashboardFragment : Fragment() {

private lateinit var dashboardViewModel: DashboardViewModel

override fun onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    dashboardViewModel =
        ViewModelProviders.of(this).get(DashboardViewModel::class.java)
    val root = inflater.inflate(R.layout.fragment_dashboard, container, false)
    val textView: TextView = root.findViewById(R.id.text_dashboard)
    dashboardViewModel.text.observe(this, Observer {
        textView.text = it
    })
    val button2 : Button = root.findViewById<Button>(R.id.temporary_button2)
    button2.setOnClickListener{
        println("clicked button 2")
        Toast.makeText(view?.context, "Button Clicked", Toast.LENGTH_LONG).show()
    }
    return root
}

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM