当前位置:首页 > 移动开发 > 正文

Android 布局之Button初步接触

2024-03-31 移动开发

1,在Activity活动对应的布局文件(layout.xml)中的LinearLayout标签下写如下代码(引用代码时请将注释去掉)

<Button
android:id="@ id/button_1"//" "代表添加一个id。其他部分是引用一个ID名为button_1。

<!--设置宽高-->
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button 1"//设置按钮显示的文字。
/>。

2,回到Activity.java文件中在onCreate方法中使用setContentView()方法加载布局文件也就是layout.xml文件。就可以在程序运行是看到我们Button的布局。

3,有一个按钮当然还需要一个响应事件。

Activity.java中创建一个按钮button1并通过findViewById()方法获取布局文件中定义的元素。

通过setOnClickListener方法添加监听,

 

Button button1= findViewById(R.id.button_1);
button1.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
添加事件。
}
});

 

温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/yidong/25660.html