Как использовать кнопки внутри фрагментов в Kotlin для разработки под Android? - PullRequest
0 голосов
/ 25 сентября 2019

Я новичок в разработке android и создал новый проект от студии android с нижней навигационной активностью в Kotlin.Помимо MainActivity.kt были сгенерированы также панель инструментов, дом и фрагменты уведомлений и их ViewModels.Когда я обрабатываю нажатие кнопки внутри класса 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()
        }
    }
}

Вот скриншот рабочей кнопки Кнопка отлично работает

Однако я не понимаю, как использовать кнопки внутри разных фрагментов.Я пытался создать функциональность для второй кнопки внутри фрагмента панели инструментов Снимок экрана второй кнопки , но я не нашел решения.Я пробовал

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 голосов
/ 25 сентября 2019

Во фрагменте нет 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;
    }
0 голосов
/ 25 сентября 2019

Вот что у меня получилось в итоге:

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
}

}

0 голосов
/ 25 сентября 2019

Попробуйте свой внутренний onViewCreated вместо onCreateView, используя getView () / view.

например:

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()
   }
 }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...