设置最简单的Button组件的方式如下所示:
1.新建一个project
2.为button在文件夹graphic下新建一个xml文件,来设置button的背景颜色,命名为“buttonelement(都可以)”
3.buttonelement.xml文件夹下输入以下代码
<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:ohos="http://schemas.huawei.com/res/ohos"
ohos:shape="rectangle">
<solid
ohos:color="#DCDCDC"/>
</shape>
这个可以根据自己的需要自行设置
4.在“MainAbilitySlice.Java中输入以下代码”
package com.example.buttonstudy.slice;
import com.example.buttonstudy.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.agp.components.Text;
import ohos.agp.utils.Color;
public class MainAbilitySlice extends AbilitySlice {
@Override
public void onStart(Intent intent) {
super.onStart(intent);
super.setUIContent(ResourceTable.Layout_ability_main);
Text text = (Text)findComponentById(ResourceTable.Id_text_helloworld);
//从定义的xml中获取Button对象
Button button = (Button)findComponentById(ResourceTable.Id_button);
if(button!=null){
button.setClickedListener(new Component.ClickedListener() {
@Override
public void onClick(Component component) {
//添加单击按钮以后发生的事情,比如这会是让text字体变色
text.setTextColor(Color.GREEN);
text.invalidate();
}
});
}
}
@Override
public void onActive() {
super.onActive();
}
@Override
public void onForeground(Intent intent) {
super.onForeground(intent);
}
}
5.在文件“ability_main.xml”中输入以下代码
<?xml version="1.0" encoding="utf-8"?>
<DirectionalLayout
xmlns:ohos="http://schemas.huawei.com/res/ohos"
ohos:height="match_parent"
ohos:width="match_parent"
ohos:orientation="vertical">
<Text
ohos:id="$+id:text_helloworld"
ohos:height="match_content"
ohos:width="match_content"
ohos:text_color="blue"
ohos:layout_alignment="horizontal_center"
ohos:text="$string:mainability_HelloWorld"
ohos:text_size="40vp"
/>
<Button
ohos:id="$+id:button"
ohos:width="match_parent"
ohos:height="match_content"
ohos:text="button"
ohos:text_size="28vp"
ohos:background_element="$graphic:buttonelement"/>
</DirectionalLayout>S
6.运行代码,如果不知道如何运行可以参考我写的另一篇博文
代码运行方法
开始界面为:
点击button以后界面为
大致就是这样,如果有什么问题可以评论或私信,也可以关注我,后续还会更新相关内容