如何在线性布局中使用视图绑定? [英] How to use View Binding with Linear Layout?
问题描述
我有一个如下所示的activity_main.xml文件.
I have a activity_main.xml file which looks like this.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_gravity="center"
tools:context=".MainActivity"
android:id="@+id/main_linear_layout">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="1"
android:layout_gravity="center_horizontal"
android:textSize="30sp"
android:id="@+id/dice_text"/>
<Button
android:id="@+id/roll_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="@string/roll"/>
</LinearLayout>
因此,当我尝试创建视图绑定并在活动"文件中使用它时, MainActivity类:AppCompatActivity(){
So when i try to create a view binding and use it in Activity file, class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
val root = binding.root
setContentView(root.main_linear_layout)
buttonClicked()
}
fun buttonClicked(): Unit {
val roll_button = binding.mainLinearLayout.roll_button
val text = binding.mainLinearLayout.dice_text
roll_button.setOnClickListener {
var randomNumber = Random().nextInt(6)+1
text.text = randomNumber.toString()
}
}
}
我有一些问题.自然地,由于线性布局将layout_gravity设置为居中,因此它应该在屏幕上居中放置(垂直和水平).在xml的设计编辑器中就是这种情况,应该是这样.
i have some issues. Naturally since the Linear Layout has layout_gravity set to center, it should be centered in the screen, both vertically and horizontally. This is the case in the design editor of the xml which is how it is supposed to be.
但是,当我运行该应用程序时,在手机中,文本和按钮都将center_horizontal而不是垂直对齐.
But when i run the app, in my phone both the text and button, aligns center_horizontal but not vertically.
我也尝试过给定center_vertical,但是不起作用.
I tried giving center_vertical also but doesn't work.
但是,如果我不使用视图绑定并使用findViewById,它将很好地工作.
But if i don't use the view binding and use findViewById , it works fine.
我从绑定中删除了mainLinearLayout.所以它只是
I have removed the mainLinearLayout from the binding. So its just
setContentView(root)
我不工作.这就是我想要的样子,这就是它的样子位于xml的设计"视图中(我已删除文本并添加了图像)
但是,当我运行它时,我得到了. 在此处输入图片描述
But, when i run it, i get this. enter image description here
P.S我刚刚开始学习android开发
P.S I have just started learning android development
推荐答案
添加
android:gravity = "center"
工作了!
这篇关于如何在线性布局中使用视图绑定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!