您好,登錄后才能下訂單哦!
在Android中,要在Fragment中動態(tài)創(chuàng)建Button,你需要遵循以下步驟:
dependencies {
implementation 'androidx.fragment:fragment-ktx:1.3.6'
}
androidx.fragment.app.Fragment
。例如:import androidx.fragment.app.Fragment
class MyFragment : Fragment() {
// ...
}
onCreateView()
方法中,使用LayoutInflater來創(chuàng)建一個新的Button實(shí)例。例如:import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
class MyFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val button = Button(context)
button.text = "Click me!"
return button
}
}
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.Toast
class MyFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val button = Button(context)
button.text = "Click me!"
button.setOnClickListener {
Toast.makeText(context, "Button clicked!", Toast.LENGTH_SHORT).show()
}
return button
}
}
onCreate()
方法中:import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
supportFragmentManager.beginTransaction()
.add(R.id.fragment_container, MyFragment())
.commit()
}
}
現(xiàn)在,當(dāng)你運(yùn)行應(yīng)用程序時,你應(yīng)該能看到一個動態(tài)創(chuàng)建的Button,并且當(dāng)你點(diǎn)擊它時,會顯示一個Toast消息。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。