最细致的鸿蒙APP学习教程——鸿蒙系统APP开发(DevEco)之四:设置按钮组件

设置最简单的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以后界面为在这里插入图片描述
大致就是这样,如果有什么问题可以评论或私信,也可以关注我,后续还会更新相关内容

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值