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

时间:2019-09-25 09:11:56

标签: java android-fragments kotlin

我是Android开发的新手,并通过Kotlin的底部导航活动从android studio创建了一个新项目。除了MainActivity.kt之外,还生成了仪表板,主页和通知Fragments及其ViewModel。当我在MainActivity类中单击按钮时,一切正常。

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()
        }
    }
}

这是工作按钮Button works fine

的屏幕截图

但是我不明白如何使用不同片段中的按钮。我试图为仪表板片段Screenshot of a second button中的第二个按钮创建功能,但没有找到解决方案。我尝试过

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()
    }

是错误的。我尝试过的另一件事是更改fragment_dashboard.xml文件并将onClick属性设置为函数名称(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" />

我试图使用如下功能:

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")
    }

}

但是这种方式不起作用,当我单击按钮时,应用程序崩溃。

任何有关如何使用片段内按钮的帮助都将得到体现。

3 个答案:

答案 0 :(得分:0)

使用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()
   }
 }

答案 1 :(得分:0)

片段中没有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;
    }

答案 2 :(得分:0)

这是最终为我解决的问题:

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
}

}