code
stringlengths
1
1.05M
repo_name
stringlengths
6
83
path
stringlengths
3
242
language
stringclasses
222 values
license
stringclasses
20 values
size
int64
1
1.05M
def outer(func): def x(*args, **kwargs): print("Before function call") value = func(*args, **kwargs) print("Outer decorator") return value return x @outer def send_wechat(body): print("微信", body) return 100 if __name__ == '__main__': res = send_wechat("你好") print(res)
2301_76469554/su_demo
8.装饰器.py
Python
unknown
338
package com.sky.controller.user; import com.sky.dto.OrdersPaymentDTO; import com.sky.dto.OrdersSubmitDTO; import com.sky.result.PageResult; import com.sky.result.Result; import com.sky.service.OrderService; import com.sky.vo.OrderPaymentVO; import com.sky.vo.OrderSubmitVO; import com.sky.vo.OrderVO; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; /** * 订单 */ @RestController("userOrderController") @RequestMapping("/user/order") @Slf4j @Api(tags = "C端订单接口") public class OrderController { @Autowired private OrderService orderService; /** * 用户下单 * * @param ordersSubmitDTO * @return */ @PostMapping("/submit") @ApiOperation("用户下单") public Result<OrderSubmitVO> submit(@RequestBody OrdersSubmitDTO ordersSubmitDTO) { log.info("用户下单:{}", ordersSubmitDTO); OrderSubmitVO orderSubmitVO = orderService.submitOrder(ordersSubmitDTO); return Result.success(orderSubmitVO); } /** * 订单支付 * * @param ordersPaymentDTO * @return */ @PutMapping("/payment") @ApiOperation("订单支付") public Result<OrderPaymentVO> payment(@RequestBody OrdersPaymentDTO ordersPaymentDTO) throws Exception { log.info("订单支付:{}", ordersPaymentDTO); OrderPaymentVO orderPaymentVO = orderService.payment(ordersPaymentDTO); log.info("生成预支付交易单:{}", orderPaymentVO); return Result.success(orderPaymentVO); } }
2301_76541209/WeChatPay
OrderController.java
Java
unknown
1,749
package com.sky.mapper; import com.github.pagehelper.Page; import com.sky.dto.GoodsSalesDTO; import com.sky.dto.OrdersPageQueryDTO; import com.sky.entity.Orders; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Select; import java.time.LocalDateTime; import java.util.List; import java.util.Map; @Mapper public interface OrderMapper { /** * 插入订单数据 * @param order */ void insert(Orders order); /** * 根据订单号查询订单 * @param orderNumber */ @Select("select * from orders where number = #{orderNumber}") Orders getByNumber(String orderNumber); /** * 修改订单信息 * @param orders */ void update(Orders orders); }
2301_76541209/WeChatPay
OrderMapper.java
Java
unknown
784
package com.sky.service; import com.sky.dto.*; import com.sky.vo.*; public interface OrderService { /** * 用户下单 * @param ordersSubmitDTO * @return */ OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO); /** * 订单支付 * @param ordersPaymentDTO * @return */ OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception; /** * 支付成功,修改订单状态 * @param outTradeNo */ void paySuccess(String outTradeNo); }
2301_76541209/WeChatPay
OrderService.java
Java
unknown
565
package com.sky.service.impl; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.github.pagehelper.Page; import com.github.pagehelper.PageHelper; import com.sky.constant.MessageConstant; import com.sky.context.BaseContext; import com.sky.dto.*; import com.sky.entity.*; import com.sky.exception.AddressBookBusinessException; import com.sky.exception.OrderBusinessException; import com.sky.exception.ShoppingCartBusinessException; import com.sky.mapper.*; import com.sky.result.PageResult; import com.sky.service.OrderService; import com.sky.utils.WeChatPayUtil; import com.sky.vo.OrderPaymentVO; import com.sky.vo.OrderStatisticsVO; import com.sky.vo.OrderSubmitVO; import com.sky.vo.OrderVO; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.CollectionUtils; import java.math.BigDecimal; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; /** * 订单 */ @Service @Slf4j public class OrderServiceImpl implements OrderService { @Autowired private OrderMapper orderMapper; @Autowired private OrderDetailMapper orderDetailMapper; @Autowired private ShoppingCartMapper shoppingCartMapper; @Autowired private UserMapper userMapper; @Autowired private AddressBookMapper addressBookMapper; @Autowired private WeChatPayUtil weChatPayUtil; /** * 用户下单 * * @param ordersSubmitDTO * @return */ @Transactional public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) { //异常情况的处理(收货地址为空、购物车为空) AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId()); if (addressBook == null) { throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL); } Long userId = BaseContext.getCurrentId(); ShoppingCart shoppingCart = new ShoppingCart(); shoppingCart.setUserId(userId); //查询当前用户的购物车数据 List<ShoppingCart> shoppingCartList = shoppingCartMapper.list(shoppingCart); if (shoppingCartList == null || shoppingCartList.size() == 0) { throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL); } //构造订单数据 Orders order = new Orders(); BeanUtils.copyProperties(ordersSubmitDTO,order); order.setPhone(addressBook.getPhone()); order.setAddress(addressBook.getDetail()); order.setConsignee(addressBook.getConsignee()); order.setNumber(String.valueOf(System.currentTimeMillis())); order.setUserId(userId); order.setStatus(Orders.PENDING_PAYMENT); order.setPayStatus(Orders.UN_PAID); order.setOrderTime(LocalDateTime.now()); //向订单表插入1条数据 orderMapper.insert(order); //订单明细数据 List<OrderDetail> orderDetailList = new ArrayList<>(); for (ShoppingCart cart : shoppingCartList) { OrderDetail orderDetail = new OrderDetail(); BeanUtils.copyProperties(cart, orderDetail); orderDetail.setOrderId(order.getId()); orderDetailList.add(orderDetail); } //向明细表插入n条数据 orderDetailMapper.insertBatch(orderDetailList); //清理购物车中的数据 shoppingCartMapper.deleteByUserId(userId); //封装返回结果 OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder() .id(order.getId()) .orderNumber(order.getNumber()) .orderAmount(order.getAmount()) .orderTime(order.getOrderTime()) .build(); return orderSubmitVO; } /** * 订单支付 * * @param ordersPaymentDTO * @return */ public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception { // 当前登录用户id Long userId = BaseContext.getCurrentId(); User user = userMapper.getById(userId); //调用微信支付接口,生成预支付交易单 JSONObject jsonObject = weChatPayUtil.pay( ordersPaymentDTO.getOrderNumber(), //商户订单号 new BigDecimal(0.01), //支付金额,单位 元 "苍穹外卖订单", //商品描述 user.getOpenid() //微信用户的openid ); if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) { throw new OrderBusinessException("该订单已支付"); } OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class); vo.setPackageStr(jsonObject.getString("package")); return vo; } /** * 支付成功,修改订单状态 * * @param outTradeNo */ public void paySuccess(String outTradeNo) { // 根据订单号查询订单 Orders ordersDB = orderMapper.getByNumber(outTradeNo); // 根据订单id更新订单的状态、支付方式、支付状态、结账时间 Orders orders = Orders.builder() .id(ordersDB.getId()) .status(Orders.TO_BE_CONFIRMED) .payStatus(Orders.PAID) .checkoutTime(LocalDateTime.now()) .build(); orderMapper.update(orders); } }
2301_76541209/WeChatPay
OrderServiceImpl.java
Java
unknown
5,911
package com.sky.controller.notify; import com.alibaba.druid.support.json.JSONUtils; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.sky.properties.WeChatProperties; import com.sky.service.OrderService; import com.wechat.pay.contrib.apache.httpclient.util.AesUtil; import lombok.extern.slf4j.Slf4j; import org.apache.http.entity.ContentType; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.BufferedReader; import java.nio.charset.StandardCharsets; import java.util.HashMap; /** * 支付回调相关接口 */ @RestController @RequestMapping("/notify") @Slf4j public class PayNotifyController { @Autowired private OrderService orderService; @Autowired private WeChatProperties weChatProperties; /** * 支付成功回调 * * @param request */ @RequestMapping("/paySuccess") public void paySuccessNotify(HttpServletRequest request, HttpServletResponse response) throws Exception { //读取数据 String body = readData(request); log.info("支付成功回调:{}", body); //数据解密 String plainText = decryptData(body); log.info("解密后的文本:{}", plainText); JSONObject jsonObject = JSON.parseObject(plainText); String outTradeNo = jsonObject.getString("out_trade_no");//商户平台订单号 String transactionId = jsonObject.getString("transaction_id");//微信支付交易号 log.info("商户平台订单号:{}", outTradeNo); log.info("微信支付交易号:{}", transactionId); //业务处理,修改订单状态、来单提醒 orderService.paySuccess(outTradeNo); //给微信响应 responseToWeixin(response); } /** * 读取数据 * * @param request * @return * @throws Exception */ private String readData(HttpServletRequest request) throws Exception { BufferedReader reader = request.getReader(); StringBuilder result = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { if (result.length() > 0) { result.append("\n"); } result.append(line); } return result.toString(); } /** * 数据解密 * * @param body * @return * @throws Exception */ private String decryptData(String body) throws Exception { JSONObject resultObject = JSON.parseObject(body); JSONObject resource = resultObject.getJSONObject("resource"); String ciphertext = resource.getString("ciphertext"); String nonce = resource.getString("nonce"); String associatedData = resource.getString("associated_data"); AesUtil aesUtil = new AesUtil(weChatProperties.getApiV3Key().getBytes(StandardCharsets.UTF_8)); //密文解密 String plainText = aesUtil.decryptToString(associatedData.getBytes(StandardCharsets.UTF_8), nonce.getBytes(StandardCharsets.UTF_8), ciphertext); return plainText; } /** * 给微信响应 * @param response */ private void responseToWeixin(HttpServletResponse response) throws Exception{ response.setStatus(200); HashMap<Object, Object> map = new HashMap<>(); map.put("code", "SUCCESS"); map.put("message", "SUCCESS"); response.setHeader("Content-type", ContentType.APPLICATION_JSON.toString()); response.getOutputStream().write(JSONUtils.toJSONString(map).getBytes(StandardCharsets.UTF_8)); response.flushBuffer(); } }
2301_76541209/WeChatPay
PayNotifyController.java
Java
unknown
4,018
from django.contrib import admin # Register your models here.
2301_76469554/Django4
01_Django快速入门/code/DjangoPro2/App/admin.py
Python
unknown
63
from django.apps import AppConfig class AppConfig(AppConfig): default_auto_field = "django.db.models.BigAutoField" name = "App"
2301_76469554/Django4
01_Django快速入门/code/DjangoPro2/App/apps.py
Python
unknown
138
from django.db import models # Create your models here.
2301_76469554/Django4
01_Django快速入门/code/DjangoPro2/App/models.py
Python
unknown
57
from django.test import TestCase # Create your tests here.
2301_76469554/Django4
01_Django快速入门/code/DjangoPro2/App/tests.py
Python
unknown
60
from django.shortcuts import render # Create your views here.
2301_76469554/Django4
01_Django快速入门/code/DjangoPro2/App/views.py
Python
unknown
63
""" ASGI config for DjangoPro2 project. It exposes the ASGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/5.1/howto/deployment/asgi/ """ import os from django.core.asgi import get_asgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "DjangoPro2.settings") application = get_asgi_application()
2301_76469554/Django4
01_Django快速入门/code/DjangoPro2/DjangoPro2/asgi.py
Python
unknown
397
""" URL configuration for DjangoPro2 project. The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/5.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path, include from user.views import * urlpatterns = [ # 路由url # 直接访问视图函数,没有使用子路由 # path('index/', index), # path('index2/', index2), # 使用子路由 # 一个应用对应一个子路由 path('user/', include('user.urls')), path("admin/", admin.site.urls), ]
2301_76469554/Django4
01_Django快速入门/code/DjangoPro2/DjangoPro2/urls.py
Python
unknown
1,038
""" WSGI config for DjangoPro2 project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/5.1/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "DjangoPro2.settings") application = get_wsgi_application()
2301_76469554/Django4
01_Django快速入门/code/DjangoPro2/DjangoPro2/wsgi.py
Python
unknown
397
#!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): """Run administrative tasks.""" os.environ.setdefault("DJANGO_SETTINGS_MODULE", "DjangoPro2.settings") try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == "__main__": main()
2301_76469554/Django4
01_Django快速入门/code/DjangoPro2/manage.py
Python
unknown
666
from django.contrib import admin from user.models import * # 后台管理系统的使用: # 1. 在这里注册对应的模型 # 2. 需要创建超级管理员的账号和密码 python manage.py createsuperuser # 3. 跟路由urls.py中添加: path('admin/', admin.site.urls), # 3. 访问后台管理系统:http://127.0.0.1:8000/admin/ admin.site.register(UserModel)
2301_76469554/Django4
01_Django快速入门/code/DjangoPro2/user/admin.py
Python
unknown
372
from django.apps import AppConfig class UserConfig(AppConfig): default_auto_field = "django.db.models.BigAutoField" name = "user"
2301_76469554/Django4
01_Django快速入门/code/DjangoPro2/user/apps.py
Python
unknown
140
from django.db import models """ 模型 <==> 表结构 类属性 <==> 字段 对象 <==> 行 """ class UserModel(models.Model): name = models.CharField(max_length=30, unique=True) # 对应的SQL:name varchar(30) age = models.IntegerField(default=18) # 对应的SQL:age int default 18 sex = models.CharField(max_length=20) # 对应的SQL:sex varchar(20) is_delete = models.BooleanField(default=False) # 对应的SQL:is_delete boolean default false def __str__(self): return f'{self.name} - {self.age}' # 用户名称 — name # 年龄 — age # 性别 — sex # 是否删除 — is_delete # 注意 # 数据迁移:models表结构一旦改变就需要重新数据迁移
2301_76469554/Django4
01_Django快速入门/code/DjangoPro2/user/models.py
Python
unknown
734
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h2>首页</h2> <p>欢迎来到我的博客</p> </body> </html>
2301_76469554/Django4
01_Django快速入门/code/DjangoPro2/user/templates/index.html
HTML
unknown
179
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>所有用户</title> </head> <body> <h2>所有用户</h2> <hr> <ul> {% for user in users %} <li>{{ user.name }}, {{ user.age }}</li> {% endfor %} </ul> </body> </html>
2301_76469554/Django4
01_Django快速入门/code/DjangoPro2/user/templates/user.html
HTML
unknown
290
from django.test import TestCase # Create your tests here.
2301_76469554/Django4
01_Django快速入门/code/DjangoPro2/user/tests.py
Python
unknown
60
from django.urls import path from user.views import * # 子路由 urlpatterns = [ # url路由写法 django v1.x,v2.x # url(r'^index/', index), # v2.x, v3.x, v4.x path('index/', index, name='index'), path('index2/', index2, name='index2'), path('users/', get_users, name='users'), ]
2301_76469554/Django4
01_Django快速入门/code/DjangoPro2/user/urls.py
Python
unknown
308
from django.contrib.auth.models import User from django.shortcuts import render from django.http import HttpResponse from user.models import * # 视图函数views def index(request): pass # # 返回响应Response # return HttpResponse('Hello Django!') # 渲染模版render,渲染html return render(request, 'index.html') # 视图函数2 def index2(request): return HttpResponse('Index2') def get_users(request): # 模型操作:获取所有用户 users = UserModel.objects.all() return render(request,'user.html', {'users': users})
2301_76469554/Django4
01_Django快速入门/code/DjangoPro2/user/views.py
Python
unknown
576
from django.contrib import admin # Register your models here.
2301_76469554/Django4
02_Django路由Router/code/DjangoPro1/App/admin.py
Python
unknown
63
from django.apps import AppConfig class AppConfig(AppConfig): default_auto_field = "django.db.models.BigAutoField" name = "App"
2301_76469554/Django4
02_Django路由Router/code/DjangoPro1/App/apps.py
Python
unknown
138
from django.db import models # Create your models here. class UserModel(models.Model): name = models.CharField(max_length=30) age = models.PositiveIntegerField() # 非负数
2301_76469554/Django4
02_Django路由Router/code/DjangoPro1/App/models.py
Python
unknown
188
from django.test import TestCase # Create your tests here.
2301_76469554/Django4
02_Django路由Router/code/DjangoPro1/App/tests.py
Python
unknown
60
from django.urls import path from App.views import * urlpatterns = [ # 首页 path('index/', index), # 用户列表 path('userlist/', user_list, name='userlist'), # 用户详情 path('userdetail/<int:uid>/', user_detail, name='userdetail'), ]
2301_76469554/Django4
02_Django路由Router/code/DjangoPro1/App/urls.py
Python
unknown
269
from django.shortcuts import render from App.models import * # 首页 def index(request): return render(request, 'index.html') # 用户列表 def user_list(request): # 获取所有用户信息 users = UserModel.objects.all() # 渲染模板 return render(request, 'user_list.html', {'users': users}) # 用户详情 def user_detail(request, uid): print('uid:', uid) user = UserModel.objects.get(pk=uid) return render(request, 'user_detail.html', {'user': user})
2301_76469554/Django4
02_Django路由Router/code/DjangoPro1/App/views.py
Python
unknown
496
""" ASGI config for DjangoPro1 project. It exposes the ASGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/5.1/howto/deployment/asgi/ """ import os from django.core.asgi import get_asgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "DjangoPro1.settings") application = get_asgi_application()
2301_76469554/Django4
02_Django路由Router/code/DjangoPro1/DjangoPro1/asgi.py
Python
unknown
397
from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = "django-insecure-wzig(f=ibdq8&wu9q)fbcb&an-pitw$zg=lfvn256@h5!7^8)0" DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", 'App.apps.AppConfig', ] MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", ] ROOT_URLCONF = "DjangoPro1.urls" TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [BASE_DIR / 'templates'] , "APP_DIRS": True, "OPTIONS": { "context_processors": [ "django.template.context_processors.debug", "django.template.context_processors.request", "django.contrib.auth.context_processors.auth", "django.contrib.messages.context_processors.messages", ], }, }, ] WSGI_APPLICATION = "DjangoPro1.wsgi.application" DATABASES = { "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": BASE_DIR / "db.sqlite3", } } AUTH_PASSWORD_VALIDATORS = [ { "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator", }, { "NAME": "django.contrib.auth.password_validation.MinimumLengthValidator", }, { "NAME": "django.contrib.auth.password_validation.CommonPasswordValidator", }, { "NAME": "django.contrib.auth.password_validation.NumericPasswordValidator", }, ] # Internationalization # https://docs.djangoproject.com/en/5.1/topics/i18n/ LANGUAGE_CODE = "en-us" TIME_ZONE = "UTC" USE_I18N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/5.1/howto/static-files/ STATIC_URL = "static/" # Default primary key field type # https://docs.djangoproject.com/en/5.1/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
2301_76469554/Django4
02_Django路由Router/code/DjangoPro1/DjangoPro1/settings.py
Python
unknown
2,440
""" URL configuration for DjangoPro1 project. The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/5.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path, include from App.views import * urlpatterns = [ # 1. 直接使用跟路由 # path('user/', index, name='index'), # 2. 使用子路由:使用include # path('user/', include('App.urls')), # 3. 使用子路由:使用include,命名空间namespace path('user/', include(('App.urls', 'App'), namespace='App')), path("admin/", admin.site.urls), ]
2301_76469554/Django4
02_Django路由Router/code/DjangoPro1/DjangoPro1/urls.py
Python
unknown
1,091
""" WSGI config for DjangoPro1 project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/5.1/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "DjangoPro1.settings") application = get_wsgi_application()
2301_76469554/Django4
02_Django路由Router/code/DjangoPro1/DjangoPro1/wsgi.py
Python
unknown
397
#!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): """Run administrative tasks.""" os.environ.setdefault("DJANGO_SETTINGS_MODULE", "DjangoPro1.settings") try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == "__main__": main()
2301_76469554/Django4
02_Django路由Router/code/DjangoPro1/manage.py
Python
unknown
666
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>首页</title> </head> <body> <h2>首页</h2> <hr> {#url路由#} <a href="/user/userlist/">url路由的方式:进入用户列表页面</a> <hr> {# 反向解析 #} {# userlist 是path路由的name值#} {# <a href="{% url 'userlist' %}">反向解析的方式:进入用户列表页面</a>#} <hr> {# 反向解析:带命名空间#} <a href="{% url 'App:userlist' %}">反向解析带命名空间的方式:进入用户列表页面</a> </body> </html>
2301_76469554/Django4
02_Django路由Router/code/DjangoPro1/templates/index.html
HTML
unknown
582
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>用户详情</title> </head> <body> <h2>用户详情</h2> <hr> <p>用户名:{{ user.name }}</p> <p>用户年龄:{{ user.age }}</p> </body> </html>
2301_76469554/Django4
02_Django路由Router/code/DjangoPro1/templates/user_detail.html
HTML
unknown
245
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>用户列表</title> </head> <body> <h2>用户列表</h2> <hr> <ul> {% for user in users %} <li> <a href="{% url 'App:userdetail' user.id %}"> {{ user.name }} - {{ user.age }} </a> </li> {% endfor %} </ul> </body> </html>
2301_76469554/Django4
02_Django路由Router/code/DjangoPro1/templates/user_list.html
HTML
unknown
363
Pod::Spec.new do |spec| spec.name = 'composeApp' spec.version = '1.0' spec.homepage = 'something must not be null' spec.source = { :http=> ''} spec.authors = '' spec.license = '' spec.summary = 'something must not be null' spec.vendored_frameworks = 'build/cocoapods/framework/ComposeApp.framework' spec.libraries = 'c++' spec.ios.deployment_target = '13.0' if !Dir.exist?('build/cocoapods/framework/ComposeApp.framework') || Dir.empty?('build/cocoapods/framework/ComposeApp.framework') raise " Kotlin framework 'ComposeApp' doesn't exist yet, so a proper Xcode project can't be generated. 'pod install' should be executed after running ':generateDummyFramework' Gradle task: ./gradlew :composeApp:generateDummyFramework Alternatively, proper pod installation is performed during Gradle sync in the IDE (if Podfile location is set)" end spec.xcconfig = { 'ENABLE_USER_SCRIPT_SANDBOXING' => 'NO', } spec.pod_target_xcconfig = { 'KOTLIN_PROJECT_PATH' => ':composeApp', 'PRODUCT_MODULE_NAME' => 'ComposeApp', } spec.script_phases = [ { :name => 'Build composeApp', :execution_position => :before_compile, :shell_path => '/bin/sh', :script => <<-SCRIPT if [ "YES" = "$OVERRIDE_KOTLIN_BUILD_IDE_SUPPORTED" ]; then echo "Skipping Gradle build task invocation due to OVERRIDE_KOTLIN_BUILD_IDE_SUPPORTED environment variable set to \"YES\"" exit 0 fi set -ev REPO_ROOT="$PODS_TARGET_SRCROOT" "$REPO_ROOT/../gradlew" -p "$REPO_ROOT" $KOTLIN_PROJECT_PATH:syncFramework \ -Pkotlin.native.cocoapods.platform=$PLATFORM_NAME \ -Pkotlin.native.cocoapods.archs="$ARCHS" \ -Pkotlin.native.cocoapods.configuration="$CONFIGURATION" SCRIPT } ] spec.resources = ['build/compose/ios/ComposeApp/compose-resources'] end
2201_76010299/kmptpc_compose_sample
composeApp/composeApp.podspec
Ruby
apache-2.0
2,324
/* * Tencent is pleased to support the open source community by making ovCompose available. * Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tencent.compose
2201_76010299/kmptpc_compose_sample
composeApp/src/androidMain/kotlin/com/tencent/compose/App.android.kt
Kotlin
apache-2.0
765
/* * Tencent is pleased to support the open source community by making ovCompose available. * Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tencent.compose import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.statusBarsPadding import androidx.compose.material.Surface import androidx.compose.ui.Modifier import com.tencent.compose.sample.mainpage.MainPage class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { Surface(modifier = Modifier.statusBarsPadding()) { MainPage() } } } }
2201_76010299/kmptpc_compose_sample
composeApp/src/androidMain/kotlin/com/tencent/compose/MainActivity.kt
Kotlin
apache-2.0
1,352
/* * Tencent is pleased to support the open source community by making ovCompose available. * Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tencent.compose import android.os.Build internal class AndroidPlatform : Platform { override val name: String = "Android ${Build.VERSION.SDK_INT}" } internal actual fun getPlatform(): Platform = AndroidPlatform()
2201_76010299/kmptpc_compose_sample
composeApp/src/androidMain/kotlin/com/tencent/compose/Platform.android.kt
Kotlin
apache-2.0
967
/* * Tencent is pleased to support the open source community by making ovCompose available. * Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tencent.compose.sample import androidx.compose.runtime.Composable import androidx.compose.ui.graphics.ImageBitmap import org.jetbrains.compose.resources.DrawableResource import org.jetbrains.compose.resources.ExperimentalResourceApi import org.jetbrains.compose.resources.imageResource @OptIn(ExperimentalResourceApi::class) @Composable actual fun rememberLocalImage(id: DrawableResource): ImageBitmap { return imageResource(resource = id) }
2201_76010299/kmptpc_compose_sample
composeApp/src/androidMain/kotlin/com/tencent/compose/sample/Images.android.kt
Kotlin
apache-2.0
1,195
/* * Tencent is pleased to support the open source community by making ovCompose available. * Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tencent.compose.sample.backhandler import androidx.compose.runtime.Composable @Composable actual fun BackHandler(enable: Boolean, onBack: () -> Unit) = androidx.activity.compose.BackHandler(enable, onBack)
2201_76010299/kmptpc_compose_sample
composeApp/src/androidMain/kotlin/com/tencent/compose/sample/backhandler/BackHandler.android.kt
Kotlin
apache-2.0
959
/* * Tencent is pleased to support the open source community by making ovCompose available. * Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tencent.compose.sample.mainpage import com.tencent.compose.sample.data.DisplayItem internal actual fun platformSections(): List<DisplayItem> { return emptyList() }
2201_76010299/kmptpc_compose_sample
composeApp/src/androidMain/kotlin/com/tencent/compose/sample/mainpage/DisplaySections.android.kt
Kotlin
apache-2.0
917
/* * Tencent is pleased to support the open source community by making ovCompose available. * Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tencent.compose class Greeting { private val platform = getPlatform() fun greet(): String { return "Hello, ${platform.name}!" } }
2201_76010299/kmptpc_compose_sample
composeApp/src/commonMain/kotlin/com/tencent/compose/Greeting.kt
Kotlin
apache-2.0
899
/* * Tencent is pleased to support the open source community by making ovCompose available. * Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tencent.compose internal interface Platform { val name: String } internal expect fun getPlatform(): Platform
2201_76010299/kmptpc_compose_sample
composeApp/src/commonMain/kotlin/com/tencent/compose/Platform.kt
Kotlin
apache-2.0
862
/* * Tencent is pleased to support the open source community by making ovCompose available. * Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tencent.compose.sample import androidx.compose.runtime.Composable import androidx.compose.ui.graphics.ImageBitmap import org.jetbrains.compose.resources.DrawableResource import org.jetbrains.compose.resources.ExperimentalResourceApi @OptIn(ExperimentalResourceApi::class) @Composable internal expect fun rememberLocalImage(id: DrawableResource): ImageBitmap
2201_76010299/kmptpc_compose_sample
composeApp/src/commonMain/kotlin/com/tencent/compose/sample/Images.kt
Kotlin
apache-2.0
1,107
/* * Tencent is pleased to support the open source community by making ovCompose available. * Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tencent.compose.sample import androidx.compose.foundation.Canvas import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.wrapContentSize import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.TileMode import androidx.compose.ui.unit.dp @Composable internal fun LinearGradientLine() { Box(modifier = Modifier.fillMaxSize().padding(50.dp).background(Color.Gray.copy(0.5f))) { Column(modifier = Modifier.wrapContentSize()) { Spacer(modifier = Modifier.size(20.dp)) Box( modifier = Modifier.size(100.dp) ) { Canvas(modifier = Modifier.fillMaxSize()) { drawLine( strokeWidth = 80f, color = Color.Red, start = Offset(0f, 0.0f), end = Offset(0.0f, 0.0f) ) } } Spacer(modifier = Modifier.size(20.dp)) Box( modifier = Modifier.size(100.dp) ) { Canvas(modifier = Modifier.fillMaxSize()) { drawLine( strokeWidth = 80f, color = Color.Blue, start = Offset(0f, 0.0f), end = Offset(0.0f, 300.0f) ) } } Spacer(modifier = Modifier.size(20.dp)) Box( modifier = Modifier.size(100.dp) ) { Canvas(modifier = Modifier.fillMaxSize()) { drawLine( strokeWidth = 80f, color = Color.Green, start = Offset(0f, 0.0f), end = Offset(300.0f, 300.0f) ) } } Spacer(modifier = Modifier.size(20.dp)) Box( modifier = Modifier.size(100.dp) ) { Canvas(modifier = Modifier.fillMaxSize()) { drawLine( strokeWidth = 80f, color = Color.Cyan, start = Offset(0f, 0.0f), end = Offset(300.0f, 0.0f) ) } } Spacer(modifier = Modifier.size(20.dp)) Box( modifier = Modifier.size(50.dp) ) { Canvas(modifier = Modifier.fillMaxSize()) { drawLine( strokeWidth = 80f, color = Color.Magenta, start = Offset(300f, 0.0f), end = Offset(0.0f, 300.0f) ) } } } Column(modifier = Modifier.wrapContentSize()) { Spacer(modifier = Modifier.size(20.dp)) Box( modifier = Modifier.size(100.dp) ) { Canvas(modifier = Modifier.fillMaxSize()) { drawLine( strokeWidth = 40f, brush = Brush.linearGradient( 0.1f to Color(0xFFBF230F), 0.3f to Color(0xFFFFC885), 0.6f to Color(0xFFE8912D), start = Offset(0.0f, 0.0f), end = Offset(600.0f, 0.0f), tileMode = TileMode.Clamp ), start = Offset(0f, 0.0f), end = Offset(0.0f, 0.0f) ) } } Spacer(modifier = Modifier.size(20.dp)) Box( modifier = Modifier.size(100.dp) ) { Canvas(modifier = Modifier.fillMaxSize()) { drawLine( strokeWidth = 40f, brush = Brush.linearGradient( 0.1f to Color(0xFFBF230F), 0.3f to Color(0xFFFFC885), 0.6f to Color(0xFFE8912D), start = Offset(0.0f, 0.0f), end = Offset(600.0f, 0.0f), tileMode = TileMode.Clamp ), start = Offset(0f, 0.0f), end = Offset(0.0f, 300.0f) ) } } Spacer(modifier = Modifier.size(20.dp)) Box( modifier = Modifier.size(100.dp) ) { Canvas(modifier = Modifier.fillMaxSize()) { drawLine( strokeWidth = 40f, brush = Brush.linearGradient( 0.1f to Color(0xFFBF230F), 0.3f to Color(0xFFFFC885), 0.6f to Color(0xFFE8912D), start = Offset(0.0f, 0.0f), end = Offset(600.0f, 0.0f), tileMode = TileMode.Clamp ), start = Offset(0f, 0.0f), end = Offset(300.0f, 300.0f) ) } } Spacer(modifier = Modifier.size(20.dp)) Box( modifier = Modifier.size(100.dp) ) { Canvas(modifier = Modifier.fillMaxSize()) { drawLine( strokeWidth = 40f, brush = Brush.linearGradient( 0.1f to Color(0xFFBF230F), 0.3f to Color(0xFFFFC885), 0.6f to Color(0xFFE8912D), start = Offset(0.0f, 0.0f), end = Offset(600.0f, 0.0f), tileMode = TileMode.Clamp ), start = Offset(0f, 0.0f), end = Offset(300.0f, 0.0f) ) } } Spacer(modifier = Modifier.size(20.dp)) Box( modifier = Modifier.size(50.dp) ) { Canvas(modifier = Modifier.fillMaxSize()) { drawLine( strokeWidth = 40f, brush = Brush.linearGradient( 0.1f to Color(0xFFBF230F), 0.3f to Color(0xFFFFC885), 0.6f to Color(0xFFE8912D), start = Offset(0.0f, 0.0f), end = Offset(600.0f, 0.0f), tileMode = TileMode.Clamp ), start = Offset(300f, 0.0f), end = Offset(0.0f, 300.0f) ) } } } } }
2201_76010299/kmptpc_compose_sample
composeApp/src/commonMain/kotlin/com/tencent/compose/sample/LinearGradientLine.kt
Kotlin
apache-2.0
8,151
/* * Tencent is pleased to support the open source community by making ovCompose available. * Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tencent.compose.sample import androidx.compose.foundation.background import androidx.compose.foundation.gestures.detectTransformGestures import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.size import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableFloatStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.unit.dp @Composable internal fun MultiTouches() { var rotationZ by remember { mutableFloatStateOf(0f) } var scale by remember { mutableFloatStateOf(1f) } var offset by remember { mutableStateOf(Offset.Zero) } Box( contentAlignment = Alignment.Center, modifier = Modifier.fillMaxSize().pointerInput(Unit) { detectTransformGestures { _, pan, zoom, rotation -> rotationZ += rotation scale *= zoom offset += pan } }) { Box( modifier = Modifier.graphicsLayer( scaleX = scale, scaleY = scale, translationX = offset.x, translationY = offset.y, rotationZ = rotationZ ).size(100.dp).background(color = Color.Blue) ) Text("scale and rotation me") } }
2201_76010299/kmptpc_compose_sample
composeApp/src/commonMain/kotlin/com/tencent/compose/sample/MultiTouches.kt
Kotlin
apache-2.0
2,513
/* * Tencent is pleased to support the open source community by making ovCompose available. * Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tencent.compose.sample.backhandler import androidx.compose.runtime.Composable @Composable internal expect fun BackHandler(enable: Boolean, onBack: () -> Unit)
2201_76010299/kmptpc_compose_sample
composeApp/src/commonMain/kotlin/com/tencent/compose/sample/backhandler/BackHandler.kt
Kotlin
apache-2.0
908
/* * Tencent is pleased to support the open source community by making ovCompose available. * Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tencent.compose.sample.data import androidx.compose.runtime.Composable import androidx.compose.runtime.Immutable import org.jetbrains.compose.resources.DrawableResource import org.jetbrains.compose.resources.ExperimentalResourceApi internal data class DisplaySection( val sectionTitle: String, val items: List<DisplayItem> ) @OptIn(ExperimentalResourceApi::class) @Immutable internal data class DisplayItem( val title: String, val img: DrawableResource, val content: @Composable () -> Unit )
2201_76010299/kmptpc_compose_sample
composeApp/src/commonMain/kotlin/com/tencent/compose/sample/data/DisplayItem.kt
Kotlin
apache-2.0
1,262
/* * Tencent is pleased to support the open source community by making ovCompose available. * Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tencent.compose.sample.mainpage import com.tencent.compose.sample.Compose1500Text import com.tencent.compose.sample.PreviewAppTabScreen import com.tencent.compose.sample.data.DisplayItem import com.tencent.compose.sample.data.DisplaySection import com.tencent.compose.sample.mainpage.material3.AlertDialogDemo import com.tencent.compose.sample.mainpage.material3.ButtonDemo import com.tencent.compose.sample.mainpage.material3.CardDemo import com.tencent.compose.sample.mainpage.material3.CheckboxDemo import com.tencent.compose.sample.mainpage.material3.DividerDemo import com.tencent.compose.sample.mainpage.material3.ListItemDemo import com.tencent.compose.sample.mainpage.material3.SimpleTab import com.tencent.compose.sample.mainpage.material3.SliderDemo import com.tencent.compose.sample.mainpage.material3.SurfaceDemo import com.tencent.compose.sample.mainpage.material3.SwitchDemo import com.tencent.compose.sample.mainpage.material3.TextButtonDemo import com.tencent.compose.sample.mainpage.material3.TextDemo import com.tencent.compose.sample.mainpage.material3.TextFieldDemo import com.tencent.compose.sample.mainpage.sectionItem.BottomAppBarDemo import com.tencent.compose.sample.mainpage.sectionItem.BouncingBallsApp import com.tencent.compose.sample.mainpage.sectionItem.CanvasDemo import com.tencent.compose.sample.mainpage.sectionItem.CarouselTransition import com.tencent.compose.sample.mainpage.sectionItem.CheckboxExamples import com.tencent.compose.sample.mainpage.sectionItem.ComposeLazy1500Image import com.tencent.compose.sample.mainpage.sectionItem.DialogExamples import com.tencent.compose.sample.mainpage.sectionItem.ImageExamplesScreen import com.tencent.compose.sample.mainpage.sectionItem.LazyLayoutDemo import com.tencent.compose.sample.mainpage.sectionItem.LazyRowDemo import com.tencent.compose.sample.mainpage.sectionItem.ProgressIndicatorExamples import com.tencent.compose.sample.mainpage.sectionItem.ScaffoldDemo import com.tencent.compose.sample.mainpage.sectionItem.SimpleImage import com.tencent.compose.sample.mainpage.sectionItem.SimpleTextPage import com.tencent.compose.sample.mainpage.sectionItem.SliderExamples import com.tencent.compose.sample.mainpage.sectionItem.SwitchExamples import com.tencent.compose.sample.mainpage.sectionItem.TabDemo import com.tencent.compose.sample.mainpage.sectionItem.TopAppBarDemo import com.tencent.compose.sample.mainpage.sectionItem.composeView1500Page import composesample.composeapp.generated.resources.Res import composesample.composeapp.generated.resources.balls import composesample.composeapp.generated.resources.carousel import composesample.composeapp.generated.resources.cat import composesample.composeapp.generated.resources.checkbox import composesample.composeapp.generated.resources.dialog import composesample.composeapp.generated.resources.dog import composesample.composeapp.generated.resources.gradient import composesample.composeapp.generated.resources.progress import composesample.composeapp.generated.resources.simple_text import composesample.composeapp.generated.resources.sliders import composesample.composeapp.generated.resources.switch import composesample.composeapp.generated.resources.text_field import org.jetbrains.compose.resources.ExperimentalResourceApi @OptIn(ExperimentalResourceApi::class) internal fun displaySections(): List<DisplaySection> { return listOf( DisplaySection( sectionTitle = "Compose Component", items = listOf( DisplayItem("dialog", Res.drawable.dialog) { DialogExamples() }, DisplayItem("switch", Res.drawable.switch) { SwitchExamples() }, DisplayItem("sliders", Res.drawable.sliders) { SliderExamples() }, DisplayItem("checkbox", Res.drawable.checkbox) { CheckboxExamples() }, DisplayItem("progress", Res.drawable.progress) { ProgressIndicatorExamples() }, DisplayItem("simple-text", Res.drawable.simple_text) { SimpleTextPage() }, DisplayItem("image-cat", Res.drawable.cat) { SimpleImage() }, DisplayItem("image-dog", Res.drawable.dog) { ImageExamplesScreen() }, DisplayItem("carousel", Res.drawable.carousel) { CarouselTransition() }, DisplayItem("scaffold", Res.drawable.text_field) { ScaffoldDemo() }, DisplayItem("Tab", Res.drawable.text_field) { TabDemo() }, DisplayItem("TopAppBar", Res.drawable.text_field) { TopAppBarDemo() }, DisplayItem("BottomAppBar", Res.drawable.text_field) { BottomAppBarDemo() }, DisplayItem("Canvas", Res.drawable.text_field) { CanvasDemo() }, DisplayItem("LazyRow", Res.drawable.text_field) { LazyRowDemo() }, DisplayItem("LazyLayout", Res.drawable.text_field) { LazyLayoutDemo() }, ) ), DisplaySection( sectionTitle = "material3", items = listOf( DisplayItem("Text", Res.drawable.text_field) { TextDemo() }, DisplayItem("Slider", Res.drawable.text_field) { SliderDemo() }, DisplayItem("Card", Res.drawable.text_field) { CardDemo() }, DisplayItem("Button", Res.drawable.text_field) { ButtonDemo() }, DisplayItem("TextButton", Res.drawable.text_field) { TextButtonDemo() }, DisplayItem("Surface", Res.drawable.text_field) { SurfaceDemo() }, DisplayItem("Checkbox", Res.drawable.text_field) { CheckboxDemo() }, DisplayItem("Tab", Res.drawable.text_field) { SimpleTab() }, DisplayItem("ListItem", Res.drawable.text_field) { ListItemDemo() }, DisplayItem("Switch", Res.drawable.text_field) { SwitchDemo() }, DisplayItem("Divider", Res.drawable.text_field) { DividerDemo() }, DisplayItem("AlertDialog", Res.drawable.text_field) { AlertDialogDemo() }, DisplayItem("TextField", Res.drawable.text_field) { TextFieldDemo() }, ) ), DisplaySection( sectionTitle = "Benchmark", items = listOf( DisplayItem("Bouncing Balls", Res.drawable.balls) { BouncingBallsApp() }, DisplayItem("1500view", Res.drawable.text_field) { composeView1500Page() }, DisplayItem("1500text", Res.drawable.text_field) { Compose1500Text() }, DisplayItem("1500image", Res.drawable.text_field) { ComposeLazy1500Image() }, DisplayItem("帖子列表", Res.drawable.gradient) { PreviewAppTabScreen() } ) ) ) } internal expect fun platformSections() : List<DisplayItem>
2201_76010299/kmptpc_compose_sample
composeApp/src/commonMain/kotlin/com/tencent/compose/sample/mainpage/DisplaySections.kt
Kotlin
apache-2.0
7,460
/* * Tencent is pleased to support the open source community by making ovCompose available. * Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tencent.compose.sample.mainpage import androidx.compose.animation.AnimatedContent import androidx.compose.animation.AnimatedContentTransitionScope import androidx.compose.animation.core.FastOutSlowInEasing import androidx.compose.animation.core.tween import androidx.compose.animation.fadeIn import androidx.compose.animation.fadeOut import androidx.compose.animation.togetherWith import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.RowScope import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.material.Icon import androidx.compose.material.Text import androidx.compose.material.TopAppBar import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.filled.ArrowBack import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.tencent.compose.sample.backhandler.BackHandler import com.tencent.compose.sample.data.DisplayItem import com.tencent.compose.sample.data.DisplaySection import com.tencent.compose.sample.rememberLocalImage import org.jetbrains.compose.resources.ExperimentalResourceApi private fun appBarTitle(openedExample: DisplayItem?, skiaRender: Boolean = true): String { val title = if (skiaRender) "Tencent Video Compose - Skia" else "Tencent Video Compose - UIKit" val childTitle = if (skiaRender) "${openedExample?.title} - Skia" else "${openedExample?.title} - UIKit" return if (openedExample != null) childTitle else title } @Composable internal fun MainPage(skiaRender: Boolean = true) { val displayItems by remember { mutableStateOf(displaySections()) } var openedExample: DisplayItem? by remember { mutableStateOf(null) } val listState = rememberLazyListState() BackHandler(openedExample != null) { openedExample = null } Column { TopAppBar( navigationIcon = { if (openedExample == null) return@TopAppBar Icon( imageVector = Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back", modifier = Modifier.clickable { openedExample = null } ) }, title = { val title = appBarTitle(openedExample, skiaRender) Text(title) } ) AnimatedContent( targetState = openedExample, transitionSpec = { val slideDirection = if (targetState != null) AnimatedContentTransitionScope.SlideDirection.Start else AnimatedContentTransitionScope.SlideDirection.End slideIntoContainer( animationSpec = tween(250, easing = FastOutSlowInEasing), towards = slideDirection ) + fadeIn(animationSpec = tween(250)) togetherWith slideOutOfContainer( animationSpec = tween(250, easing = FastOutSlowInEasing), towards = slideDirection ) + fadeOut(animationSpec = tween(250)) } ) { target -> if (target == null) { LazyColumn(state = listState) { items(displayItems) { displayItem -> Section(displayItem) { clickItem -> openedExample = clickItem } } item { Spacer(Modifier.fillMaxWidth().height(20.dp)) } } } else { Box(Modifier.fillMaxSize()) { target.content() } } } } } @Composable private fun Section(displaySection: DisplaySection, itemClick: (displayItem: DisplayItem) -> Unit) { Column { SectionTitle(displaySection.sectionTitle) val chunkedItems = displaySection.items.chunked(3) chunkedItems.forEach { rowItems -> Row(verticalAlignment = Alignment.CenterVertically) { rowItems.forEach { BoxItem(it, itemClick) } repeat(3 - rowItems.size) { Spacer(Modifier.weight(0.33f)) } } } } } @Composable private fun SectionTitle(title: String) { Row( Modifier.fillMaxWidth().height(34.dp).background(Color.Black.copy(alpha = 0.11f)), verticalAlignment = Alignment.CenterVertically, ) { Spacer(Modifier.fillMaxHeight().width(10.dp)) Text( text = title, fontSize = 16.sp, color = Color.Black.copy(alpha = 0.7f), fontWeight = FontWeight.Medium ) } } @OptIn(ExperimentalResourceApi::class) @Composable private fun RowScope.BoxItem( displayItem: DisplayItem, itemClick: (displayItem: DisplayItem) -> Unit ) { Column( Modifier.weight(0.33f) .height(86.dp) .border(0.3.dp, color = Color.LightGray).clickable { itemClick(displayItem) }, horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center, ) { Image( modifier = Modifier.width(34.dp).size(28.dp), bitmap = rememberLocalImage(displayItem.img), contentDescription = null ) Spacer(Modifier.fillMaxWidth().height(10.dp)) Text(text = displayItem.title, fontSize = 14.sp, color = Color.Black.copy(alpha = 0.7f)) } }
2201_76010299/kmptpc_compose_sample
composeApp/src/commonMain/kotlin/com/tencent/compose/sample/mainpage/MainPage.kt
Kotlin
apache-2.0
7,479
package com.tencent.compose.sample.mainpage.material3 import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.wrapContentHeight import androidx.compose.foundation.layout.wrapContentWidth import androidx.compose.material3.AlertDialog import androidx.compose.material3.AlertDialogDefaults import androidx.compose.material3.Button import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import org.jetbrains.compose.ui.tooling.preview.Preview @OptIn(ExperimentalMaterial3Api::class) @Preview() @Composable internal fun AlertDialogDemo(){ val openDialog = remember { mutableStateOf(true) } Button(onClick = { openDialog.value = true }) { Text("Open dialog") } if (openDialog.value) { AlertDialog( onDismissRequest = { // Dismiss the dialog when the user clicks outside the dialog or on the back // button. If you want to disable that functionality, simply use an empty // onDismissRequest. openDialog.value = false } ) { Surface( modifier = Modifier.wrapContentWidth().wrapContentHeight(), shape = MaterialTheme.shapes.large, tonalElevation = AlertDialogDefaults.TonalElevation, ) { Column(modifier = Modifier.padding(16.dp)) { Text( text = "This area typically contains the supportive text " + "which presents the details regarding the Dialog's purpose." ) Spacer(modifier = Modifier.height(24.dp)) TextButton( onClick = { openDialog.value = false }, modifier = Modifier.align(Alignment.End), ) { Text("Confirm") } } } } } }
2201_76010299/kmptpc_compose_sample
composeApp/src/commonMain/kotlin/com/tencent/compose/sample/mainpage/material3/AlertDialog.kt
Kotlin
apache-2.0
2,548
package com.tencent.compose.sample.mainpage.material3 import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.size import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Favorite import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.Icon import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import org.jetbrains.compose.ui.tooling.preview.Preview @Composable @Preview() internal fun ButtonDemo(){ var isFavorite by remember { mutableStateOf(false) } Button( onClick = { isFavorite = !isFavorite }, contentPadding = ButtonDefaults.ButtonWithIconContentPadding, ) { Icon( Icons.Filled.Favorite, contentDescription = if (isFavorite) "取消收藏" else "添加收藏", tint = if (isFavorite) Color.Red else Color.White ) Spacer(Modifier.size(ButtonDefaults.IconSpacing)) Text("Like") } }
2201_76010299/kmptpc_compose_sample
composeApp/src/commonMain/kotlin/com/tencent/compose/sample/mainpage/material3/Button.kt
Kotlin
apache-2.0
1,305
package com.tencent.compose.sample.mainpage.material3 import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.size import androidx.compose.material3.Card import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import org.jetbrains.compose.ui.tooling.preview.Preview @Preview() @Composable internal fun CardDemo(){ Card(Modifier.size(width = 180.dp, height = 100.dp)) { Box(Modifier.fillMaxSize()) { Text("Card content", Modifier.align(Alignment.Center)) } } }
2201_76010299/kmptpc_compose_sample
composeApp/src/commonMain/kotlin/com/tencent/compose/sample/mainpage/material3/Card.kt
Kotlin
apache-2.0
699
package com.tencent.compose.sample.mainpage.material3 import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.selection.toggleable import androidx.compose.material3.Checkbox import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.semantics.Role import androidx.compose.ui.semantics.role import androidx.compose.ui.semantics.semantics import androidx.compose.ui.unit.dp import org.jetbrains.compose.ui.tooling.preview.Preview @Composable @Preview() internal fun CheckboxDemo() { // 1. 状态管理:使用 remember 保留状态,避免重组时重置;mutableStateOf 实现状态可观察 // checkedState:当前复选框选中状态(true=选中,false=未选中) // onStateChange:状态变更回调,接收新状态值用于更新 checkedState val (checkedState, onStateChange) = remember { mutableStateOf(true) } // 2. 布局容器:Row 横向排列复选框和文本,模拟 Material3 列表项交互区域 Row( modifier = Modifier .fillMaxWidth() .height(56.dp) .toggleable( value = checkedState, onValueChange = { isChecked -> onStateChange(isChecked) }, role = Role.Checkbox, ) .padding(horizontal = 16.dp), verticalAlignment = Alignment.CenterVertically, ) { // 3. 复选框组件:Material3 标准 Checkbox,仅负责状态展示,不单独处理点击 Checkbox( // 绑定状态:控制复选框是否显示选中样式 checked = checkedState, onCheckedChange = null, ) // 4. 文本描述:展示复选框对应的选项文本,使用主题样式保证全局风格统一 Text( text = "Option selection", style = MaterialTheme.typography.bodyLarge, modifier = Modifier .padding(start = 16.dp) .semantics { this.role = Role.Checkbox } ) } }
2201_76010299/kmptpc_compose_sample
composeApp/src/commonMain/kotlin/com/tencent/compose/sample/mainpage/material3/Checkbox.kt
Kotlin
apache-2.0
2,491
package com.tencent.compose.sample.mainpage.material3 import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box import androidx.compose.material.DropdownMenu import androidx.compose.material.DropdownMenuItem import androidx.compose.material.ExperimentalMaterialApi import androidx.compose.material.ExposedDropdownMenuDefaults.TrailingIcon import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import org.jetbrains.compose.ui.tooling.preview.Preview @OptIn(ExperimentalMaterialApi::class) @Composable @Preview() internal fun CustomDropdownMenu( // 移除 expanded 和 onExpandedChange,其他参数按需保留 ) { // 组件内部管理展开状态 var expanded by remember { mutableStateOf(false) } // 点击时切换内部状态(无需外部传入回调) val toggleExpanded = { expanded = !expanded } // 主体内容容器(可点击区域) Box(modifier = Modifier.clickable { toggleExpanded() }) { Text("选择选项") // 调用 TrailingIcon,直接使用内部状态和切换逻辑 TrailingIcon( expanded = expanded, onIconClick = toggleExpanded // 点击图标也切换内部状态 ) } // 下拉菜单(根据内部 expanded 状态显示/隐藏) if (expanded) { DropdownMenu( expanded = expanded, onDismissRequest = { expanded = false } // 点击外部关闭菜单 ) { DropdownMenuItem(onClick = { /* 选项1逻辑 */ }) { Text("选项1") } DropdownMenuItem(onClick = { /* 选项2逻辑 */ }) { Text("选项2") } } } }
2201_76010299/kmptpc_compose_sample
composeApp/src/commonMain/kotlin/com/tencent/compose/sample/mainpage/material3/CustomDropdownMenu.kt
Kotlin
apache-2.0
1,935
package com.tencent.compose.sample.mainpage.material3 import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.material3.Divider import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import org.jetbrains.compose.ui.tooling.preview.Preview @Preview() @Composable internal fun DividerDemo() { Column( modifier = Modifier .fillMaxSize() .padding(16.dp) ) { // 标题 Text( text = "设置选项", style = MaterialTheme.typography.headlineSmall, modifier = Modifier.padding(bottom = 8.dp) ) // 标题与内容之间的分隔线 Divider() // 列表项1 Text( text = "账户设置", modifier = Modifier.padding(vertical = 16.dp) ) // 列表项之间的分隔线 Divider( thickness = 2.dp, // 自定义厚度 color = Color.Gray // 自定义颜色 ) // 列表项2 Text( text = "通知管理", modifier = Modifier.padding(vertical = 16.dp) ) // 细分隔线 Divider( thickness = Dp.Hairline // 极细的分隔线 ) // 列表项3 Text( text = "隐私政策", modifier = Modifier.padding(vertical = 16.dp) ) // 带边距的分隔线 Divider( modifier = Modifier.padding(horizontal = 32.dp) // 左右留空 ) // 列表项4 Text( text = "关于我们", modifier = Modifier.padding(vertical = 16.dp) ) } }
2201_76010299/kmptpc_compose_sample
composeApp/src/commonMain/kotlin/com/tencent/compose/sample/mainpage/material3/Divider.kt
Kotlin
apache-2.0
1,981
package com.tencent.compose.sample.mainpage.material3 import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.CircleShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ArrowForward import androidx.compose.material.icons.filled.Email import androidx.compose.material.icons.filled.Info import androidx.compose.material.icons.filled.Star import androidx.compose.material3.Icon import androidx.compose.material3.ListItem import androidx.compose.material3.ListItemDefaults import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Switch import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import org.jetbrains.compose.ui.tooling.preview.Preview @Preview() @Composable internal fun ListItemDemo(){ Column( modifier = Modifier.fillMaxSize() ) { Text( text = "不同样式的 ListItem 示例", style = MaterialTheme.typography.titleLarge, modifier = Modifier.padding(16.dp) ) // 1. 基础列表项 - 只有标题 ListItem( headlineContent = { Text("基础列表项") } ) // 2. 带前缀图标的列表项 ListItem( headlineContent = { Text("带前缀图标的项") }, leadingContent = { Icon( imageVector = Icons.Default.Email, contentDescription = "邮件图标" ) } ) // 3. 带后缀内容的列表项 ListItem( headlineContent = { Text("带后缀内容的项") }, trailingContent = { Text( "新", style = MaterialTheme.typography.labelSmall, color = Color.Red ) } ) // 4. 带副标题的列表项 ListItem( headlineContent = { Text("带副标题的项") }, supportingContent = { Text("这是副标题内容,用于补充说明") }, leadingContent = { Icon( imageVector = Icons.Default.Info, contentDescription = "信息图标" ) } ) // 5. 带前缀文字和后缀图标的列表项 ListItem( headlineContent = { Text("通知设置") }, overlineContent = { Text("系统") }, // overline 在标题上方 leadingContent = { Box( modifier = Modifier .size(40.dp) .background(Color.Blue, CircleShape), contentAlignment = Alignment.Center ) { Text( "S", color = Color.White, fontWeight = FontWeight.Bold ) } }, trailingContent = { Switch( checked = true, onCheckedChange = {} ) } ) // 6. 带多个后缀元素的列表项 ListItem( headlineContent = { Text("多元素后缀") }, supportingContent = { Text("显示时间和箭头") }, trailingContent = { Row(verticalAlignment = Alignment.CenterVertically) { Text( "10:30", style = MaterialTheme.typography.bodySmall, color = Color.Gray ) Icon( imageVector = Icons.Default.ArrowForward, contentDescription = "箭头", modifier = Modifier.size(20.dp) ) } } ) // 7. 自定义颜色的列表项 ListItem( headlineContent = { Text("自定义颜色项") }, colors = ListItemDefaults.colors( containerColor = Color.LightGray.copy(alpha = 0.3f), headlineColor = Color.Blue ), leadingContent = { Icon( imageVector = Icons.Default.Star, contentDescription = "星星图标" ) } ) } }
2201_76010299/kmptpc_compose_sample
composeApp/src/commonMain/kotlin/com/tencent/compose/sample/mainpage/material3/ListItem.kt
Kotlin
apache-2.0
4,911
package com.tencent.compose.sample.mainpage.material3 import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.padding import androidx.compose.material3.Slider import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import org.jetbrains.compose.ui.tooling.preview.Preview @Preview @Composable internal fun SliderDemo() { // 用 rememberSaveable 保存滑块位置,横竖屏切换时不丢失状态 var sliderPosition by rememberSaveable { mutableStateOf(0f) } Column(modifier = Modifier.padding(horizontal = 16.dp)) { Text(text = "当前值 :" + sliderPosition ) Slider( value = sliderPosition, // 滑块拖动时更新值 onValueChange = { sliderPosition = it } ) } }
2201_76010299/kmptpc_compose_sample
composeApp/src/commonMain/kotlin/com/tencent/compose/sample/mainpage/material3/Slider.kt
Kotlin
apache-2.0
1,069
package com.tencent.compose.sample.mainpage.material3 import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import org.jetbrains.compose.ui.tooling.preview.Preview @Preview() @Composable internal fun SurfaceDemo() { // 状态变量委托正常工作(依赖上面导入的 getValue/setValue) var count by remember { mutableStateOf(0) } // Surface 组件可正常识别(依赖上面导入的 Surface) Surface( onClick = { count++ } // 点击时自增计数,语法正常 ) { Text("Clickable Surface. Count: $count") } }
2201_76010299/kmptpc_compose_sample
composeApp/src/commonMain/kotlin/com/tencent/compose/sample/mainpage/material3/Surface.kt
Kotlin
apache-2.0
809
package com.tencent.compose.sample.mainpage.material3 import androidx.compose.foundation.layout.size import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Check import androidx.compose.material3.Icon import androidx.compose.material3.Switch import androidx.compose.material3.SwitchDefaults import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.semantics.contentDescription import androidx.compose.ui.semantics.semantics import org.jetbrains.compose.ui.tooling.preview.Preview @Preview() @Composable internal fun SwitchDemo(){ var checked by remember { mutableStateOf(true) } Switch( modifier = Modifier.semantics { contentDescription = "Demo with icon" }, checked = checked, onCheckedChange = { checked = it }, thumbContent = { if (checked) { // Icon isn't focusable, no need for content description Icon( imageVector = Icons.Filled.Check, contentDescription = null, modifier = Modifier.size(SwitchDefaults.IconSize), ) } }, ) }
2201_76010299/kmptpc_compose_sample
composeApp/src/commonMain/kotlin/com/tencent/compose/sample/mainpage/material3/Switch.kt
Kotlin
apache-2.0
1,377
package com.tencent.compose.sample.mainpage.material3 import androidx.compose.foundation.layout.Column import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.MaterialTheme import androidx.compose.material3.PrimaryTabRow import androidx.compose.material3.Tab import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.text.style.TextOverflow import org.jetbrains.compose.ui.tooling.preview.Preview @OptIn(ExperimentalMaterial3Api::class) @Preview() @Composable internal fun SimpleTab(){ var state by remember { mutableStateOf(0) } val titles = listOf("Tab 1", "Tab 2", "Tab 3 with lots of text") Column { PrimaryTabRow(selectedTabIndex = state) { titles.forEachIndexed { index, title -> Tab( selected = state == index, onClick = { state = index }, text = { Text(text = title, maxLines = 2, overflow = TextOverflow.Ellipsis) }, ) } } Text( modifier = Modifier.align(Alignment.CenterHorizontally), text = "Text tab ${state + 1} selected", style = MaterialTheme.typography.bodyLarge, ) } }
2201_76010299/kmptpc_compose_sample
composeApp/src/commonMain/kotlin/com/tencent/compose/sample/mainpage/material3/Tab.kt
Kotlin
apache-2.0
1,518
package com.tencent.compose.sample.mainpage.material3 import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.text.buildAnnotatedString import org.jetbrains.compose.ui.tooling.preview.Preview @Composable @Preview internal fun TextDemo( modifier: Modifier = Modifier ) { val annotatedString: AnnotatedString = buildAnnotatedString { append("Build better apps faster with ") } // 使用 Material3 主题样式的 Text 组件 Text( text = annotatedString, // 继承主题默认样式 style = MaterialTheme.typography.bodyLarge, // 接收外部修饰符 modifier = modifier ) }
2201_76010299/kmptpc_compose_sample
composeApp/src/commonMain/kotlin/com/tencent/compose/sample/mainpage/material3/Text.kt
Kotlin
apache-2.0
832
package com.tencent.compose.sample.mainpage.material3 import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import org.jetbrains.compose.ui.tooling.preview.Preview @Preview() @Composable internal fun TextButtonDemo() { // 用于记录点击次数的状态变量(会触发UI重组) var clickCount by remember { mutableStateOf(0) } TextButton( onClick = { clickCount++ } ) { Text("点击我 ($clickCount)") } }
2201_76010299/kmptpc_compose_sample
composeApp/src/commonMain/kotlin/com/tencent/compose/sample/mainpage/material3/TextButton.kt
Kotlin
apache-2.0
714
package com.tencent.compose.sample.mainpage.material3 import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.material3.Button import androidx.compose.material3.Text import androidx.compose.material3.TextField import androidx.compose.runtime.Composable import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import org.jetbrains.compose.ui.tooling.preview.Preview @Preview() @Composable internal fun TextFieldDemo() { var text by remember { mutableStateOf("") } val isError by remember { derivedStateOf { text.length < 3 && text.isNotEmpty() } } Column( modifier = Modifier .fillMaxSize() .padding(16.dp), verticalArrangement = Arrangement.Center ) { TextField( value = text, onValueChange = { newValue -> text = newValue }, label = { Text("请输入至少3个字符") }, placeholder = { Text("在此处输入内容") }, isError = isError, supportingText = { if (isError) { Text("输入内容长度至少为3个字符") } }, modifier = Modifier.fillMaxWidth() ) Spacer(modifier = Modifier.padding(vertical = 8.dp)) Button( onClick = { // 这里可以添加点击按钮后的逻辑,比如提交输入的内容 println("输入的内容是:$text") }, enabled = text.length >= 3 ) { Text("提交") } } }
2201_76010299/kmptpc_compose_sample
composeApp/src/commonMain/kotlin/com/tencent/compose/sample/mainpage/material3/Textfield.kt
Kotlin
apache-2.0
2,115
// AppHomeCompose.kt package com.tencent.compose.sample import androidx.compose.animation.animateColorAsState import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.* import androidx.compose.foundation.shape.CircleShape import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.filter import kotlinx.coroutines.flow.map import kotlinx.coroutines.delay import kotlinx.coroutines.flow.collectLatest import kotlin.random.Random import kotlinx.coroutines.launch import kotlinx.coroutines.yield import androidx.compose.foundation.Image import androidx.compose.material.Button import androidx.compose.material.Divider import androidx.compose.material.IconButton import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.unit.Dp // 如果你的 rememberLocalImage 与 Res 在别的包,请改成对应包名 import com.tencent.compose.sample.rememberLocalImage import composesample.composeapp.generated.resources.Res //import composesample.composeapp.generated.resources.cat1 //import composesample.composeapp.generated.resources.cat2 import composesample.composeapp.generated.resources.image_cat import composesample.composeapp.generated.resources.image_dog import org.jetbrains.compose.resources.ExperimentalResourceApi /** * Single-file Compose implementation of: * - Home with top tabs (Follow/Trend) * - Follow feed list with refresh & load more * - Trending with nested tabs (Recommend / Nearby / ...) * * Focused on UI only; replace placeholders (images, real data) as needed. */ /* ------------------------------ Top-level screen ------------------------------ */ @Composable internal fun AppHomeScreen( modifier: Modifier = Modifier, onSettingsClick: () -> Unit = {} ) { val resFollow = "关注" val resTrend = "热门" val titles = listOf(resFollow, resTrend) var currentIndex by remember { mutableStateOf(0) } Column(modifier = modifier.fillMaxSize()) { TopTabs( titles = titles, selectedIndex = currentIndex, onTabSelected = { idx -> currentIndex = idx }, onSettingsClick = onSettingsClick ) Box(modifier = Modifier.fillMaxSize()) { when (currentIndex) { 0 -> FeedListPage(pageType = "follow") else -> TrendingPage() } } } } @Composable private fun TopTabs( titles: List<String>, selectedIndex: Int, onTabSelected: (Int) -> Unit, onSettingsClick: () -> Unit ) { val background = Color(0xFFF7F7F7) val textFocused = Color(0xFF111111) val textUnfocused = Color(0xFF888888) val indicatorColor = Color(0xFFFF3B30) Row( modifier = Modifier .fillMaxWidth() .height(56.dp) .background(background) .padding(horizontal = 8.dp), verticalAlignment = Alignment.CenterVertically ) { Row( modifier = Modifier.weight(1f), verticalAlignment = Alignment.CenterVertically ) { titles.forEachIndexed { i, title -> val selected = i == selectedIndex val textColor by animateColorAsState(if (selected) textFocused else textUnfocused) Column( modifier = Modifier .padding(horizontal = 10.dp) .clickable { onTabSelected(i) }, horizontalAlignment = Alignment.CenterHorizontally ) { Text( text = title, fontSize = 17.sp, fontWeight = if (selected) FontWeight.Bold else FontWeight.Normal, color = textColor ) Spacer(modifier = Modifier.height(6.dp)) Box( modifier = Modifier .height(3.dp) .widthIn(min = 24.dp) ) { if (selected) { Box( modifier = Modifier .height(3.dp) .fillMaxWidth() .background(indicatorColor) ) } } } } } IconButton(onClick = onSettingsClick) { Box( modifier = Modifier .size(22.dp) .clip(CircleShape) .background(Color(0xFFAAC7FF)) ) } } } @Composable internal fun FeedListPage(pageType: String) { var isRefreshing by remember { mutableStateOf(false) } var isLoadingMore by remember { mutableStateOf(false) } val listState = rememberLazyListState() val items = remember { mutableStateListOf<FeedItemModel>() } val coroutineScope = rememberCoroutineScope() LaunchedEffect(pageType) { items.clear() items.addAll(generateSampleFeeds(start = 0, count = 100)) } LaunchedEffect(listState) { snapshotFlow { val last = listState.layoutInfo.visibleItemsInfo.lastOrNull()?.index last }.map { it ?: -1 } .distinctUntilChanged() .filter { idx -> idx >= 0 } .collectLatest { lastIndex -> val total = items.size if (lastIndex >= total - 3 && !isLoadingMore) { isLoadingMore = true delay(700) val newItems = generateSampleFeeds(start = items.size, count = 20) if (newItems.isNotEmpty()) { items.addAll(newItems) } isLoadingMore = false } } } Column(modifier = Modifier.fillMaxSize()) { Row( modifier = Modifier .fillMaxWidth() .padding(horizontal = 12.dp, vertical = 8.dp), verticalAlignment = Alignment.CenterVertically ) { Button(onClick = { if (!isRefreshing) { isRefreshing = true coroutineScope.launch { delay(800) items.clear() items.addAll(generateSampleFeeds(start = 0, count = 100)) isRefreshing = false yield() } } }) { Text(text = if (isRefreshing) "正在刷新..." else "刷新") } Spacer(modifier = Modifier.width(12.dp)) Text(text = "共 ${items.size} 条", color = Color(0xFF666666)) } Divider(color = Color(0xFFECECEC)) LazyColumn( modifier = Modifier.fillMaxSize(), state = listState, contentPadding = PaddingValues(vertical = 8.dp) ) { items(items, key = { it.id }) { item -> FeedCard(item = item) } item { Spacer(modifier = Modifier.height(8.dp)) if (isLoadingMore) { Box(modifier = Modifier.fillMaxWidth(), contentAlignment = Alignment.Center) { Text(text = "加载中...", color = Color(0xFF777777)) } } else { Box(modifier = Modifier.fillMaxWidth(), contentAlignment = Alignment.Center) { Text(text = "上滑加载更多", color = Color(0xFFAAAAAA)) } } Spacer(modifier = Modifier.height(16.dp)) } } } } @Composable internal fun TrendingPage() { val types = listOf( "推荐", "附近", "榜单", "明星", "搞笑", "社会", "测试" ) var selected by remember { mutableStateOf(0) } Column(modifier = Modifier.fillMaxSize()) { Row( modifier = Modifier .fillMaxWidth() .background(Color(0xFFF2F2F2)) .padding(vertical = 6.dp), verticalAlignment = Alignment.CenterVertically ) { val density = LocalDensity.current types.forEachIndexed { i, t -> val selectedColor by animateColorAsState(if (i == selected) Color.Black else Color(0xFF777777)) Text( text = t, modifier = Modifier .padding(horizontal = 12.dp, vertical = 8.dp) .clickable { selected = i }, color = selectedColor, fontSize = 15.sp ) } } Box(modifier = Modifier.fillMaxSize()) { when (selected) { 0 -> FeedListPage(pageType = "recommend") 1 -> FeedListPage(pageType = "nearby") else -> FeedListPage(pageType = "other_$selected") } } } } private data class FeedItemModel( val id: String, val nick: String, val content: String ) private fun generateSampleFeeds(start: Int, count: Int): List<FeedItemModel> { return (start until start + count).map { FeedItemModel( id = it.toString(), nick = "用户_$it", content = "这是示例内容($it),用于展示 Feed 列表。随机一句话:${sampleSentence()}" ) } } private fun sampleSentence(): String { val samples = listOf( "今天天气不错。", "刚刚吃了个好吃的午餐。", "去看了一场电影,推荐!", "学习 Compose 中……", "这是一个示例条目。", "音乐让人放松。" ) return samples[Random.nextInt(samples.size)] } @OptIn(ExperimentalResourceApi::class) @Composable private fun FeedCard(item: FeedItemModel) { Column( modifier = Modifier .fillMaxWidth() .padding(horizontal = 12.dp, vertical = 8.dp) .background(Color.White) .padding(12.dp) ) { Row(verticalAlignment = Alignment.CenterVertically) { Avatar(size = 40.dp) Spacer(modifier = Modifier.width(8.dp)) Column { Text(text = item.nick, fontWeight = FontWeight.SemiBold, fontSize = 15.sp) Spacer(modifier = Modifier.height(4.dp)) Text(text = "来自 · 手机", color = Color(0xFF777777), fontSize = 12.sp) } } Spacer(modifier = Modifier.height(8.dp)) Text(text = item.content, fontSize = 14.sp, color = Color(0xFF222222)) Spacer(modifier = Modifier.height(8.dp)) Row(modifier = Modifier.fillMaxWidth()) { Image( bitmap = rememberLocalImage(Res.drawable.image_cat), contentDescription = null, modifier = Modifier .weight(1f) .height(160.dp), contentScale = ContentScale.Crop ) Spacer(modifier = Modifier.width(8.dp)) Image( bitmap = rememberLocalImage(Res.drawable.image_dog), contentDescription = null, modifier = Modifier .weight(1f) .height(160.dp), contentScale = ContentScale.Crop ) } Spacer(modifier = Modifier.height(8.dp)) Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween ) { Text(text = "转发 12", fontSize = 12.sp, color = Color(0xFF666666)) Text(text = "评论 34", fontSize = 12.sp, color = Color(0xFF666666)) Text(text = "点赞 56", fontSize = 12.sp, color = Color(0xFF666666)) } } } @Composable private fun Avatar(size: Dp) { Box( modifier = Modifier .size(size) .clip(CircleShape) .background(Color(0xFFCCCCCC)) ) } @Composable internal fun AppHomePreview() { MaterialTheme { AppHomeScreen(modifier = Modifier.fillMaxSize()) } }
2201_76010299/kmptpc_compose_sample
composeApp/src/commonMain/kotlin/com/tencent/compose/sample/mainpage/sectionItem/AppHomePageView.kt
Kotlin
apache-2.0
12,853
package com.tencent.compose.sample.mainpage.sectionItem import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.shape.CircleShape import androidx.compose.material.AppBarDefaults import androidx.compose.material.BottomAppBar import androidx.compose.material.ContentAlpha import androidx.compose.material.DrawerValue import androidx.compose.material.FloatingActionButton import androidx.compose.material.FloatingActionButtonDefaults import androidx.compose.material.Icon import androidx.compose.material.IconButton import androidx.compose.material.LocalContentAlpha import androidx.compose.material.Scaffold import androidx.compose.material.Text import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Add import androidx.compose.material.icons.filled.Favorite import androidx.compose.material.icons.filled.Home import androidx.compose.material.icons.filled.Menu import androidx.compose.material.icons.filled.Settings import androidx.compose.material.rememberDrawerState import androidx.compose.material.rememberScaffoldState import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import kotlinx.coroutines.launch import org.jetbrains.compose.ui.tooling.preview.Preview @Preview() @Composable internal fun BottomAppBarDemo() { // 1. 状态管理:记录「首页」按钮的选中状态(模拟底部导航的选中逻辑) var isHomeSelected by remember { mutableStateOf(true) } var scaffoldState = rememberScaffoldState( drawerState = rememberDrawerState(initialValue = DrawerValue.Closed) ) var isFavorite by remember { mutableStateOf(false) } // 2. 定义颜色常量:统一管理,便于后续修改主题 val appBarBgColor = Color(0xFF6200EE) val selectedIconColor = Color.White val unselectedIconColor = Color(0xFFE0E0E0) val fabColor = Color(0xFFBB86FC) // 3. 使用 Scaffold 作为父容器: // - 提供完整的页面结构(底部导航栏 + 悬浮按钮 + 主内容区) // - 自动处理 BottomAppBar 与 FAB 的布局关系(如嵌入效果) // 4. 创建协程作用域,用于处理需要在协程中执行的操作(如抽屉状态变更) val coroutineScope = rememberCoroutineScope() Scaffold( scaffoldState = scaffoldState, // 底部导航栏配置 bottomBar = { BottomAppBar( windowInsets = AppBarDefaults.bottomAppBarWindowInsets, backgroundColor = appBarBgColor, cutoutShape = CircleShape, elevation = 8.dp ) { CompositionLocalProvider(LocalContentAlpha provides ContentAlpha.high) { IconButton( onClick = { coroutineScope.launch { if (scaffoldState.drawerState.isOpen){ scaffoldState.drawerState.close() } else{ scaffoldState.drawerState.open() } } } ) { Icon( imageVector = Icons.Filled.Menu, contentDescription = "打开侧边菜单", tint = selectedIconColor ) } } Spacer( modifier = Modifier .weight(1f) .fillMaxWidth() ) IconButton( onClick = { isHomeSelected = true } ) { Icon( imageVector = Icons.Filled.Home, contentDescription = "首页", tint = if (isHomeSelected) selectedIconColor else unselectedIconColor ) } // 收藏按钮 IconButton( onClick = { isFavorite = !isFavorite } ) { Icon( imageVector = Icons.Filled.Favorite, contentDescription = if (isFavorite) "取消收藏" else "添加收藏", // 未选中状态(浅灰色) tint = if (isFavorite) Color.Red else Color.White ) } // 设置按钮(新增,丰富功能场景) IconButton( onClick = { /* 实际项目中可打开设置页面 */ } ) { Icon( imageVector = Icons.Filled.Settings, contentDescription = "设置", tint = unselectedIconColor // 未选中状态(浅灰色) ) } } }, // 悬浮按钮配置(与 BottomAppBar 配合实现嵌入效果) floatingActionButton = { FloatingActionButton( onClick = { /* 实际项目中可触发核心操作,如「添加内容」「发布」 */ }, backgroundColor = fabColor, elevation = FloatingActionButtonDefaults.elevation( defaultElevation = 8.dp, pressedElevation = 12.dp ) ) { Icon( imageVector = Icons.Filled.Add, contentDescription = "添加内容", tint = Color.White ) } }, // 悬浮按钮位置:居中并嵌入 BottomAppBar(Docked 模式) floatingActionButtonPosition = androidx.compose.material.FabPosition.Center, isFloatingActionButtonDocked = true, // 抽屉菜单内容 drawerContent = { Text( text = "侧边抽屉菜单", modifier = Modifier.padding(16.dp) ) } ) { innerPadding -> // 4. 主内容区域: // - innerPadding:Scaffold 自动计算的内边距(避免内容被 BottomAppBar 或状态栏遮挡) // - 实际项目中可替换为 List、Column 等组件 Text( text = if (isHomeSelected) "首页内容区" else "其他页面内容区", modifier = Modifier .padding(innerPadding) .fillMaxWidth() .height(400.dp), color = Color.Black, fontSize = 18.sp ) } }
2201_76010299/kmptpc_compose_sample
composeApp/src/commonMain/kotlin/com/tencent/compose/sample/mainpage/sectionItem/BottomAppBar.kt
Kotlin
apache-2.0
7,222
/* * Tencent is pleased to support the open source community by making ovCompose available. * Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tencent.compose.sample.mainpage.sectionItem import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.clickable import androidx.compose.foundation.gestures.detectTapGestures import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.BoxWithConstraints import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.shape.CircleShape import androidx.compose.material.Button import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.MutableState import androidx.compose.runtime.key import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.snapshots.SnapshotStateList import androidx.compose.runtime.withFrameNanos import androidx.compose.ui.Modifier import androidx.compose.ui.composed import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Color import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.unit.dp import com.tencent.compose.sample.mainpage.sectionItem.BouncingBall.Companion.setCount import kotlin.math.PI import kotlin.math.cos import kotlin.math.max import kotlin.math.roundToInt import kotlin.math.sin import kotlin.random.Random private fun Modifier.noRippleClickable(onClick: (Offset) -> Unit): Modifier = composed { clickable( indication = null, interactionSource = remember { MutableInteractionSource() }) { }.pointerInput(Unit) { detectTapGestures(onTap = { println("tap offset = $it") onClick(it) }) } } private var areaWidth = 0 private var areaHeight = 0 @Composable internal fun BouncingBallsApp(initialBallsCount: Int = 10) { val items = remember { val list = mutableStateListOf<BouncingBall>() list.addAll(generateSequence { BouncingBall.createBouncingBall() }.take(initialBallsCount)) list } BoxWithConstraints( modifier = Modifier.fillMaxWidth() .fillMaxHeight() .border(width = 1.dp, color = Color.Black) .noRippleClickable { items += BouncingBall.createBouncingBall(offset = it) } ) { areaWidth = maxWidth.value.roundToInt() areaHeight = maxHeight.value.roundToInt() Balls(items) Column { Row { Text("count: ${items.size}") Spacer(Modifier.width(16.dp)) Button(onClick = { items.setCount(10) }) { Text("10") } Spacer(Modifier.width(16.dp)) Button(onClick = { items.setCount(items.size + 10) }) { Text("+10") } Spacer(Modifier.width(16.dp)) Button(onClick = { items.setCount(items.size + 100) }) { Text("+100") } } } } LaunchedEffect(Unit) { var lastTime = 0L var dt = 0L while (true) { withFrameNanos { time -> dt = time - lastTime if (lastTime == 0L) { dt = 0 } lastTime = time items.forEach { it.recalculate(areaWidth, areaHeight, dt.toFloat()) } } } } } @Composable private fun Balls(items: List<BouncingBall>) { items.forEachIndexed { ix, ball -> key(ix) { Box( modifier = Modifier .offset( x = (ball.circle.x.value - ball.circle.r).dp, y = (ball.circle.y.value - ball.circle.r).dp ).size((2 * ball.circle.r).dp) .background(ball.color, CircleShape) ) } } } private class Circle( var x: MutableState<Float>, var y: MutableState<Float>, val r: Float ) { constructor(x: Float, y: Float, r: Float) : this( mutableStateOf(x), mutableStateOf(y), r ) fun moveCircle(s: Float, angle: Float, width: Int, height: Int, r: Float) { x.value = (x.value + s * sin(angle)).coerceAtLeast(r).coerceAtMost(width.toFloat() - r) y.value = (y.value + s * cos(angle)).coerceAtLeast(r).coerceAtMost(height.toFloat() - r) } } private fun calculatePosition(circle: Circle, boundingWidth: Int, boundingHeight: Int): Position { val southmost = circle.y.value + circle.r val northmost = circle.y.value - circle.r val westmost = circle.x.value - circle.r val eastmost = circle.x.value + circle.r return when { southmost >= boundingHeight -> Position.TOUCHES_SOUTH northmost <= 0 -> Position.TOUCHES_NORTH eastmost >= boundingWidth -> Position.TOUCHES_EAST westmost <= 0 -> Position.TOUCHES_WEST else -> Position.INSIDE } } private enum class Position { INSIDE, TOUCHES_SOUTH, TOUCHES_NORTH, TOUCHES_WEST, TOUCHES_EAST } private class BouncingBall( val circle: Circle, val velocity: Float, var angle: Double, val color: Color = Color.Red ) { fun recalculate(width: Int, height: Int, dt: Float) { val position = calculatePosition(circle, width, height) val dtMillis = dt / 1000000 when (position) { Position.TOUCHES_SOUTH -> angle = PI - angle Position.TOUCHES_EAST -> angle = -angle Position.TOUCHES_WEST -> angle = -angle Position.TOUCHES_NORTH -> angle = PI - angle Position.INSIDE -> angle } circle.moveCircle( velocity * (dtMillis.coerceAtMost(500f) / 1000), angle.toFloat(), width, height, circle.r ) } companion object { private val random = Random(100) private val angles = listOf(PI / 4, -PI / 3, 3 * PI / 4, -PI / 6, -1.1 * PI) private val colors = listOf(Color.Red, Color.Black, Color.Green, Color.Magenta) private fun randomOffset(): Offset { return Offset( x = random.nextInt(100, 700).toFloat(), y = random.nextInt(100, 500).toFloat() ) } fun createBouncingBall(offset: Offset = randomOffset()): BouncingBall { return BouncingBall( circle = Circle(x = offset.x, y = offset.y, r = random.nextInt(10, 50).toFloat()), velocity = random.nextInt(100, 200).toFloat(), angle = angles.random(), color = colors.random().copy(alpha = max(0.3f, random.nextFloat())) ) } fun SnapshotStateList<BouncingBall>.setCount(count: Int) { when { size > count -> removeRange(count - 1, lastIndex) size < count -> addAll(generateSequence { createBouncingBall() }.take(count - size)) } } } }
2201_76010299/kmptpc_compose_sample
composeApp/src/commonMain/kotlin/com/tencent/compose/sample/mainpage/sectionItem/BouncingBalls.kt
Kotlin
apache-2.0
8,259
package com.tencent.compose.sample.mainpage.sectionItem import androidx.compose.foundation.Canvas import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.dp import org.jetbrains.compose.ui.tooling.preview.Preview @Preview() @Composable internal fun CanvasDemo() { // 使用Column垂直布局,子元素会从上到下排列 Column( modifier = Modifier.size(300.dp) ) { // 文本说明放在上方 Text( text = "饼图:红色部分占80%,黄色部分占20%", modifier = Modifier.padding(bottom = 16.dp) ) // 饼图放在下方 Canvas( contentDescription = "饼图:红色部分占80%,黄色部分占20%", modifier = Modifier.size(200.dp) ) { // 绘制红色部分(80%) drawCircle( color = Color.Red, radius = size.width / 2 ) // 绘制黄色部分(20%) drawArc( color = Color.Yellow, startAngle = 0f, sweepAngle = 360f * 0.20f, // 20%对应的角度 useCenter = true, topLeft = Offset(0f, (size.height - size.width) / 2f), size = Size(size.width, size.width) ) } } }
2201_76010299/kmptpc_compose_sample
composeApp/src/commonMain/kotlin/com/tencent/compose/sample/mainpage/sectionItem/Canvas.kt
Kotlin
apache-2.0
1,680
/* * Tencent is pleased to support the open source community by making ovCompose available. * Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tencent.compose.sample.mainpage.sectionItem import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.width import androidx.compose.foundation.pager.HorizontalPager import androidx.compose.foundation.pager.PagerState import androidx.compose.foundation.pager.rememberPagerState import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.unit.dp import kotlin.math.absoluteValue @OptIn(ExperimentalFoundationApi::class) internal fun Modifier.carouselTransition( start: Float, stop: Float, index: Int, pagerState: PagerState ) = graphicsLayer { val pageOffset = ((pagerState.currentPage - index) + pagerState.currentPageOffsetFraction).absoluteValue val transformation = androidx.compose.ui.util.lerp( start = start, stop = stop, fraction = 1f - pageOffset.coerceIn( 0f, 1f ) ) alpha = transformation } @OptIn(ExperimentalFoundationApi::class) @Composable internal fun CarouselTransition() { val pageCount = 3 val pagerState: PagerState = rememberPagerState(pageCount = { pageCount }) Column( Modifier.width(300.dp).height(300.dp).background(Color.Green), horizontalAlignment = Alignment.CenterHorizontally ) { HorizontalPager( modifier = Modifier.fillMaxSize().background(Color.Blue), state = pagerState, contentPadding = PaddingValues(horizontal = 10.dp), pageSpacing = 20.dp ) { page: Int -> Box( modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center ) { Text("文本:${page}", color = Color.White) Box( modifier = Modifier .fillMaxSize() .carouselTransition( start = 0.6f, stop = 0.0f, index = page, pagerState = pagerState ).background(Color.Black) ) {} Box(Modifier .align(Alignment.BottomEnd) .height(16.dp) .width(16.dp).background(Color.Green) .carouselTransition( start = .0f, stop = 1.0f, index = page, pagerState = pagerState )) } } } }
2201_76010299/kmptpc_compose_sample
composeApp/src/commonMain/kotlin/com/tencent/compose/sample/mainpage/sectionItem/CarouselTransition.kt
Kotlin
apache-2.0
3,813
/* * Tencent is pleased to support the open source community by making ovCompose available. * Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tencent.compose.sample.mainpage.sectionItem import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.material.Checkbox import androidx.compose.material.Text import androidx.compose.material.TriStateCheckbox import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.testTag import androidx.compose.ui.state.ToggleableState import androidx.compose.ui.unit.dp import org.jetbrains.compose.ui.tooling.preview.Preview @Preview @Composable internal fun CheckboxExamples() { Column( modifier = Modifier .padding(16.dp) .fillMaxSize(), verticalArrangement = Arrangement.spacedBy(32.dp), horizontalAlignment = Alignment.CenterHorizontally, ) { Column { Text("Minimal checkbox example") CheckboxMinimalExample() } Column { Text("Parent checkbox example") CheckboxParentExample() } } } @Preview // [START android_compose_components_checkbox_minimal] @Composable private fun CheckboxMinimalExample() { var checked by remember { mutableStateOf(true) } Row( verticalAlignment = Alignment.CenterVertically, ) { Text( "Minimal checkbox" ) Checkbox( checked = checked, onCheckedChange = { checked = it } ) } Text( if (checked) "Checkbox is checked" else "Checkbox is unchecked" ) } // [END android_compose_components_checkbox_minimal] @Preview // [START android_compose_components_checkbox_parent] @Composable private fun CheckboxParentExample() { // Initialize states for the child checkboxes val childCheckedStates = remember { mutableStateListOf(false, false, false) } // Compute the parent state based on children's states val parentState = when { childCheckedStates.all { it } -> ToggleableState.On childCheckedStates.none { it } -> ToggleableState.Off else -> ToggleableState.Indeterminate } Column { // Parent TriStateCheckbox Row( verticalAlignment = Alignment.CenterVertically, ) { Text("Select all") TriStateCheckbox( state = parentState, onClick = { // Determine new state based on current state val newState = parentState != ToggleableState.On childCheckedStates.forEachIndexed { index, _ -> childCheckedStates[index] = newState } } ) } // Child Checkboxes childCheckedStates.forEachIndexed { index, checked -> Row( verticalAlignment = Alignment.CenterVertically, ) { Text("Option ${index + 1}") Checkbox( checked = checked, onCheckedChange = { isChecked -> // Update the individual child state childCheckedStates[index] = isChecked }, modifier = Modifier.testTag("checkbox${index + 1}"), ) } } } if (childCheckedStates.all { it }) { Text("All options selected") } } // [END android_compose_components_checkbox_parent]
2201_76010299/kmptpc_compose_sample
composeApp/src/commonMain/kotlin/com/tencent/compose/sample/mainpage/sectionItem/Checkbox.kt
Kotlin
apache-2.0
4,608
package com.tencent.compose.sample import androidx.compose.foundation.border import androidx.compose.foundation.layout.* import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material.Text import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp @Composable internal fun Compose1500Text() { Column( modifier = Modifier .verticalScroll(rememberScrollState()) .fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally ) { repeat(1500) { index -> Text( text = "Compose1500Text Item #$index", fontSize = 16.sp, modifier = Modifier .width(300.dp) .height(50.dp) .border(1.dp, Color.Gray) .padding(10.dp) ) } } }
2201_76010299/kmptpc_compose_sample
composeApp/src/commonMain/kotlin/com/tencent/compose/sample/mainpage/sectionItem/Compose1500Text.kt
Kotlin
apache-2.0
1,076
/* * Tencent is pleased to support the open source community by making ovCompose available. * Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tencent.compose.sample.mainpage.sectionItem import androidx.compose.foundation.* import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.alpha import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.RectangleShape import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.graphics.painter.Painter import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.tencent.compose.sample.rememberLocalImage import composesample.composeapp.generated.resources.Res import composesample.composeapp.generated.resources.image_cat import org.jetbrains.compose.resources.ExperimentalResourceApi @OptIn(ExperimentalResourceApi::class) @Composable internal fun ComposeLazy1500Image() { val gap = 12.dp LazyColumn( modifier = Modifier .fillMaxWidth() .background(Color.White), verticalArrangement = Arrangement.spacedBy(gap), contentPadding = PaddingValues(vertical = gap) ) { items(1500) { FollowUserItem() } } } @OptIn(ExperimentalResourceApi::class) @Composable internal fun FollowUserItem() { val bmp = rememberLocalImage(Res.drawable.image_cat) val ratio = bmp.width.toFloat() / bmp.height.toFloat() Row( modifier = Modifier .fillMaxWidth() .padding(horizontal = 16.dp), verticalAlignment = Alignment.CenterVertically, ) { Box( modifier = Modifier .weight(1f) .aspectRatio(ratio) ) { Image( bitmap = bmp, contentDescription = null, modifier = Modifier.fillMaxSize(), contentScale = ContentScale.Fit, ) } } }
2201_76010299/kmptpc_compose_sample
composeApp/src/commonMain/kotlin/com/tencent/compose/sample/mainpage/sectionItem/ComposeLazy1500Image.kt
Kotlin
apache-2.0
2,904
/* * Tencent is pleased to support the open source community by making ovCompose available. * Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:OptIn(ExperimentalResourceApi::class, ExperimentalResourceApi::class) package com.tencent.compose.sample.mainpage.sectionItem import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.aspectRatio import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.draw.BlurredEdgeTreatment import androidx.compose.ui.draw.blur import androidx.compose.ui.draw.clip import androidx.compose.ui.geometry.Rect import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.BlendMode import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.ColorFilter import androidx.compose.ui.graphics.ColorMatrix import androidx.compose.ui.graphics.Outline import androidx.compose.ui.graphics.Path import androidx.compose.ui.graphics.Shape import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.Density import androidx.compose.ui.unit.LayoutDirection import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.tencent.compose.sample.rememberLocalImage import composesample.composeapp.generated.resources.Res import composesample.composeapp.generated.resources.home_icon import composesample.composeapp.generated.resources.image_dog import org.jetbrains.compose.resources.ExperimentalResourceApi import org.jetbrains.compose.resources.painterResource import org.jetbrains.compose.ui.tooling.preview.Preview private val examples: List<ItemTitle> = listOf( ItemTitle("ContentScaleExample") { ContentScaleExample() }, ItemTitle("ClipImageExample") { ClipImageExample() }, ItemTitle("ClipRoundedCorner") { ClipRoundedCorner() }, ItemTitle("CustomClippingShape") { CustomClippingShape() }, ItemTitle("ImageWithBorder") { ImageWithBorder() }, ItemTitle("ImageRainbowBorder") { ImageRainbowBorder() }, ItemTitle("ImageAspectRatio") { ImageAspectRatio() }, ItemTitle("ImageColorFilter") { ImageColorFilter() }, ItemTitle("ImageBlendMode") { ImageBlendMode() }, ItemTitle("ImageColorMatrix") { ImageColorMatrix() }, ItemTitle("ImageAdjustBrightnessContrast") { ImageAdjustBrightnessContrast() }, ItemTitle("ImageInvertColors") { ImageInvertColors() }, ItemTitle("ImageBlur") { ImageBlur() }, ItemTitle("ImageBlurBox") { ImageBlurBox() }, ItemTitle("ImageBlurEdgeTreatment") { ImageBlurEdgeTreatment() } ) private class ItemTitle( val name: String, val content: @Composable () -> Unit ) @Preview @Composable internal fun ImageExamplesScreen(start: Int = 0, end: Int = examples.size) { if (start < 0 || end > examples.size) { throw RuntimeException("ImageExamplesScreen input error, start=$start, end=$end") } val items = examples.subList(start, end) LazyColumn(Modifier.padding(top = 15.dp, bottom = 15.dp)) { items(items) { item -> Column(modifier = Modifier.fillMaxWidth()) { Text( text = item.name, fontSize = 20.sp, fontWeight = FontWeight.Bold ) item.content() } } } } @Composable private fun ContentScaleExample() { // [START android_compose_content_scale] val imageModifier = Modifier .size(150.dp) .border(BorderStroke(1.dp, Color.Black)) .background(Color.Yellow) Image( bitmap = rememberLocalImage(Res.drawable.image_dog), contentDescription = "", contentScale = ContentScale.Fit, modifier = imageModifier ) // [END android_compose_content_scale] } @Preview @Composable private fun ClipImageExample() { // [START android_compose_clip_image] Image( bitmap = rememberLocalImage(Res.drawable.image_dog), contentDescription = "", contentScale = ContentScale.Crop, modifier = Modifier .size(200.dp) .clip(CircleShape) ) // [END android_compose_clip_image] } @Preview @Composable private fun ClipRoundedCorner() { // [START android_compose_clip_image_rounded_corner] Image( bitmap = rememberLocalImage(Res.drawable.image_dog), contentDescription = "", contentScale = ContentScale.Crop, modifier = Modifier .size(200.dp) .clip(RoundedCornerShape(16.dp)) ) // [END android_compose_clip_image_rounded_corner] } @Preview @Composable private fun CustomClippingShape() { // [START android_compose_custom_clipping_shape] class SquashedOval : Shape { override fun createOutline( size: Size, layoutDirection: LayoutDirection, density: Density ): Outline { val path = Path().apply { // We create an Oval that starts at ¼ of the width, and ends at ¾ of the width of the container. addOval( Rect( left = size.width / 4f, top = 0f, right = size.width * 3 / 4f, bottom = size.height ) ) } return Outline.Generic(path = path) } } Box(modifier = Modifier.background(Color.Green)) { Image( bitmap = rememberLocalImage(Res.drawable.image_dog), contentDescription = "", contentScale = ContentScale.Crop, modifier = Modifier .size(200.dp) .clip(SquashedOval()) ) } // [END android_compose_custom_clipping_shape] } @Preview @Composable private fun ImageWithBorder() { // [START android_compose_image_border] val borderWidth = 4.dp Image( bitmap = rememberLocalImage(Res.drawable.image_dog), contentDescription = "", contentScale = ContentScale.Crop, modifier = Modifier .size(150.dp) .border( BorderStroke(borderWidth, Color.Yellow), CircleShape ) .padding(borderWidth) .clip(CircleShape) ) // [END android_compose_image_border] } @Preview @Composable private fun ImageRainbowBorder() { // [START android_compose_image_rainbow_border] val rainbowColorsBrush = remember { Brush.sweepGradient( listOf( Color(0xFF9575CD), Color(0xFFBA68C8), Color(0xFFE57373), Color(0xFFFFB74D), Color(0xFFFFF176), Color(0xFFAED581), Color(0xFF4DD0E1), Color(0xFF9575CD) ) ) } val borderWidth = 15.dp Image( bitmap = rememberLocalImage(Res.drawable.image_dog), contentDescription = "", contentScale = ContentScale.Crop, modifier = Modifier .size(150.dp) .border( BorderStroke(borderWidth, rainbowColorsBrush), CircleShape ) .padding(borderWidth) .clip(CircleShape) ) val density = LocalDensity.current.density val pxValue = borderWidth * density println("ImageRainbowBorder to px$pxValue") Box( modifier = Modifier.size(100.dp).background(Color.Black).border( BorderStroke(borderWidth, rainbowColorsBrush), CircleShape ) ) { } // [END android_compose_image_rainbow_border] } @Composable @Preview private fun ImageAspectRatio() { // [START android_compose_image_aspect_ratio] Image( bitmap = rememberLocalImage(Res.drawable.image_dog), contentDescription = "", modifier = Modifier.aspectRatio(16f / 9f) ) // [END android_compose_image_aspect_ratio] } @Composable @Preview private fun ImageColorFilter() { // [START android_compose_image_color_filter] Column { Image( modifier = Modifier.size(32.dp), bitmap = rememberLocalImage(Res.drawable.home_icon), contentDescription = "", colorFilter = ColorFilter.tint(Color.Red, BlendMode.SrcAtop) ) Text(text = "首页") } // [END android_compose_image_color_filter] } @Preview @Composable private fun ImageBlendMode() { // [START android_compose_image_blend_mode] Image( bitmap = rememberLocalImage(Res.drawable.image_dog), contentDescription = "", colorFilter = ColorFilter.tint(Color.Green, blendMode = BlendMode.Darken) ) // [END android_compose_image_blend_mode] } @Preview @Composable private fun ImageColorMatrix() { // [START android_compose_image_colormatrix] Image( bitmap = rememberLocalImage(Res.drawable.image_dog), contentDescription = "", colorFilter = ColorFilter.colorMatrix(ColorMatrix().apply { setToSaturation(0f) }) ) // [END android_compose_image_colormatrix] } @Preview @Composable private fun ImageAdjustBrightnessContrast() { // [START android_compose_image_brightness] val contrast = 2f // 0f..10f (1 should be default) val brightness = -180f // -255f..255f (0 should be default) val colorMatrix = floatArrayOf( contrast, 0f, 0f, 0f, brightness, 0f, contrast, 0f, 0f, brightness, 0f, 0f, contrast, 0f, brightness, 0f, 0f, 0f, 1f, 0f ) Image( bitmap = rememberLocalImage(Res.drawable.image_dog), contentDescription = "", colorFilter = ColorFilter.colorMatrix(ColorMatrix(colorMatrix)) ) // [END android_compose_image_brightness] } @Preview @Composable private fun ImageInvertColors() { // [START android_compose_image_invert_colors] val colorMatrix = floatArrayOf( -1f, 0f, 0f, 0f, 255f, 0f, -1f, 0f, 0f, 255f, 0f, 0f, -1f, 0f, 255f, 0f, 0f, 0f, 1f, 0f ) Image( bitmap = rememberLocalImage(Res.drawable.image_dog), contentDescription = "", colorFilter = ColorFilter.colorMatrix(ColorMatrix(colorMatrix)) ) // [END android_compose_image_invert_colors] } @Preview @Composable private fun ImageBlur() { var blurRadius by remember { mutableStateOf(40.dp) } // [START android_compose_image_blur] Image( bitmap = rememberLocalImage(Res.drawable.image_dog), contentDescription = "", contentScale = ContentScale.Crop, modifier = Modifier .clickable { blurRadius = if (blurRadius == 40.dp) { 0.dp } else { 40.dp } } .blur( radiusX = blurRadius, radiusY = blurRadius, edgeTreatment = BlurredEdgeTreatment(RoundedCornerShape(8.dp)) ) ) // [END android_compose_image_blur] } @Preview @Composable private fun ImageBlurBox() { // [START android_compose_image_blur] var blurRadius by remember { mutableStateOf(40.dp) } // [START android_compose_image_blur] Box( modifier = Modifier .background(Color.Black) .size(150.dp) .blur(blurRadius).clickable { blurRadius = if (blurRadius == 40.dp) { 0.dp } else { 40.dp } } ) { Image( bitmap = rememberLocalImage(Res.drawable.image_dog), contentDescription = "", contentScale = ContentScale.Crop, modifier = Modifier .size(150.dp) ) } // [END android_compose_image_blur] } @Preview @Composable private fun ImageBlurEdgeTreatment() { // [START android_compose_image_blur_edge_treatment] Image( bitmap = rememberLocalImage(Res.drawable.image_dog), contentDescription = "", contentScale = ContentScale.Crop, modifier = Modifier .size(150.dp) .blur( radiusX = 10.dp, radiusY = 10.dp, edgeTreatment = BlurredEdgeTreatment.Unbounded ) .clip(RoundedCornerShape(8.dp)) ) // / [END android_compose_image_blur_edge_treatment] }
2201_76010299/kmptpc_compose_sample
composeApp/src/commonMain/kotlin/com/tencent/compose/sample/mainpage/sectionItem/CustomizeImageSnippets.kt
Kotlin
apache-2.0
14,122
/* * Tencent is pleased to support the open source community by making ovCompose available. * Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tencent.compose.sample.mainpage.sectionItem import androidx.compose.foundation.Image import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.wrapContentSize import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.AlertDialog import androidx.compose.material.Button import androidx.compose.material.Card import androidx.compose.material.Surface import androidx.compose.material.Text import androidx.compose.material.TextButton import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Info import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.ImageBitmap import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.compose.ui.window.Dialog import androidx.compose.ui.window.DialogProperties import com.tencent.compose.sample.rememberLocalImage import composesample.composeapp.generated.resources.Res import composesample.composeapp.generated.resources.feathertop import org.jetbrains.compose.resources.ExperimentalResourceApi import org.jetbrains.compose.ui.tooling.preview.Preview @OptIn(ExperimentalResourceApi::class) @Preview // [START android_compose_components_dialogparent] @Composable internal fun DialogExamples() { // [START_EXCLUDE] val openMinimalDialog = remember { mutableStateOf(false) } val openDialogWithImage = remember { mutableStateOf(false) } val openFullScreenDialog = remember { mutableStateOf(false) } // [END_EXCLUDE] val openAlertDialog = remember { mutableStateOf(false) } // [START_EXCLUDE] Column( modifier = Modifier .padding(16.dp) .fillMaxSize(), verticalArrangement = Arrangement.spacedBy(8.dp), horizontalAlignment = Alignment.CenterHorizontally, ) { Text("Click the following button to toggle the given dialog example.") Button( onClick = { openMinimalDialog.value = !openMinimalDialog.value } ) { Text("Minimal dialog component") } Button( onClick = { openDialogWithImage.value = !openDialogWithImage.value } ) { Text("Dialog component with an image") } Button( onClick = { openAlertDialog.value = !openAlertDialog.value } ) { Text("Alert dialog component with buttons") } Button( onClick = { openFullScreenDialog.value = !openFullScreenDialog.value } ) { Text("Full screen dialog") } // [END_EXCLUDE] when { // [START_EXCLUDE] openMinimalDialog.value -> { MinimalDialog( onDismissRequest = { openMinimalDialog.value = false }, ) } openDialogWithImage.value -> { DialogWithImage( onDismissRequest = { openDialogWithImage.value = false }, onConfirmation = { openDialogWithImage.value = false println("Confirmation registered") // Add logic here to handle confirmation. }, bitmap = rememberLocalImage(Res.drawable.feathertop), imageDescription = "", ) } openFullScreenDialog.value -> { FullScreenDialog( onDismissRequest = { openFullScreenDialog.value = false }, ) } // [END_EXCLUDE] openAlertDialog.value -> { AlertDialogExample( onDismissRequest = { openAlertDialog.value = false }, onConfirmation = { openAlertDialog.value = false println("Confirmation registered") // Add logic here to handle confirmation. }, dialogTitle = "Alert dialog example", dialogText = "This is an example of an alert dialog with buttons.", icon = Icons.Default.Info ) } } } } // [END android_compose_components_dialogparent] // [START android_compose_components_minimaldialog] @Composable private fun MinimalDialog(onDismissRequest: () -> Unit) { Dialog(onDismissRequest = { onDismissRequest() }) { Card( modifier = Modifier .fillMaxWidth() .height(200.dp) .padding(16.dp) .clickable { onDismissRequest() }, shape = RoundedCornerShape(16.dp), ) { Text( text = "This is a minimal dialog", modifier = Modifier .fillMaxSize() .wrapContentSize(Alignment.Center), textAlign = TextAlign.Center, ) } } } // [END android_compose_components_minimaldialog] // [START android_compose_components_dialogwithimage] @Composable private fun DialogWithImage( onDismissRequest: () -> Unit, onConfirmation: () -> Unit, bitmap: ImageBitmap, imageDescription: String, ) { Dialog(onDismissRequest = { onDismissRequest() }) { // Draw a rectangle shape with rounded corners inside the dialog Card ( modifier = Modifier .fillMaxWidth() .height(375.dp) .padding(16.dp), shape = RoundedCornerShape(16.dp), ) { Column( modifier = Modifier .fillMaxSize(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally, ) { Image( bitmap = bitmap, contentDescription = imageDescription, contentScale = ContentScale.Fit, modifier = Modifier .height(160.dp) ) Text( text = "This is a dialog with buttons and an image.", modifier = Modifier.padding(16.dp), ) Row( modifier = Modifier .fillMaxWidth(), horizontalArrangement = Arrangement.Center, ) { TextButton( onClick = { onDismissRequest() }, modifier = Modifier.padding(8.dp), ) { Text("Dismiss") } TextButton( onClick = { onConfirmation() }, modifier = Modifier.padding(8.dp), ) { Text("Confirm") } } } } } } // [END android_compose_components_dialogwithimage] // [START android_compose_components_alertdialog] @Composable private fun AlertDialogExample( onDismissRequest: (() -> Unit)? = null, onConfirmation: (() -> Unit)? = null, dialogTitle: String = "dialogTitle", dialogText: String = "dialogText", icon: ImageVector = Icons.Default.Info, ) { AlertDialog( title = { Text(text = dialogTitle) }, text = { Text(text = dialogText) }, onDismissRequest = { onDismissRequest?.invoke() }, confirmButton = { TextButton( onClick = { onConfirmation?.invoke() } ) { Text("Confirm") } }, dismissButton = { TextButton( onClick = { onDismissRequest?.invoke() } ) { Text("Dismiss") } } ) } // [END android_compose_components_alertdialog] // [START android_compose_components_fullscreendialog] @Composable private fun FullScreenDialog(onDismissRequest: () -> Unit) { Dialog( onDismissRequest = { onDismissRequest() }, properties = DialogProperties( usePlatformDefaultWidth = false, dismissOnBackPress = true, ), ) { Surface ( modifier = Modifier .fillMaxSize(), ) { Column( modifier = Modifier .fillMaxSize(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally, ) { Text( text = "This is a full screen dialog", textAlign = TextAlign.Center, ) TextButton(onClick = { onDismissRequest() }) { Text("Dismiss") } } } } } // [END android_compose_components_fullscreendialog]
2201_76010299/kmptpc_compose_sample
composeApp/src/commonMain/kotlin/com/tencent/compose/sample/mainpage/sectionItem/Dialog.kt
Kotlin
apache-2.0
10,400
/* * Tencent is pleased to support the open source community by making ovCompose available. * Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tencent.compose.sample.mainpage.sectionItem import androidx.compose.foundation.LocalIndication import androidx.compose.foundation.gestures.detectTapGestures import androidx.compose.foundation.indication import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.interaction.PressInteraction import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.material.Card import androidx.compose.material.DropdownMenu import androidx.compose.material.DropdownMenuItem import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.layout.onSizeChanged import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.unit.DpOffset import androidx.compose.ui.unit.dp @Composable internal fun DropdownMenu( name: String = "点我的任意位置", dropdownMenuItems: List<DropdownItem> = List(10) { DropdownItem("DropdownItem$it") }, modifier: Modifier = Modifier, onItemClick: (DropdownItem) -> Unit = {} ) { var isContextMenuVisible by rememberSaveable { mutableStateOf(false) } var pressOffset by remember { mutableStateOf(0.dp) } var itemHeight by remember { mutableStateOf(0.dp) } val density = LocalDensity.current val interactionSource = remember { MutableInteractionSource() } Card( elevation = 40.dp, modifier = modifier .onSizeChanged { itemHeight = with(density) { it.height.toDp() } } ) { Box( modifier = Modifier .fillMaxWidth() .indication(interactionSource, LocalIndication.current) .pointerInput(true) { detectTapGestures( onLongPress = { isContextMenuVisible = true }, onPress = { isContextMenuVisible = true val press = PressInteraction.Press(it) interactionSource.emit(press) tryAwaitRelease() interactionSource.emit(PressInteraction.Release(press)) }, onTap = { isContextMenuVisible = true }, onDoubleTap = { isContextMenuVisible = true } ) } .padding(16.dp) ) { Text(text = name) } DropdownMenu( expanded = isContextMenuVisible, offset = DpOffset(x = 0.dp, y = 0.dp), onDismissRequest = { isContextMenuVisible = false }) { dropdownMenuItems.forEach { item -> run { DropdownMenuItem( onClick = { onItemClick(item) isContextMenuVisible = false } ) { Text(text = item.text) } } } } } } internal data class DropdownItem( val text: String )
2201_76010299/kmptpc_compose_sample
composeApp/src/commonMain/kotlin/com/tencent/compose/sample/mainpage/sectionItem/DropdownMenu.kt
Kotlin
apache-2.0
4,535
/* * Tencent is pleased to support the open source community by making ovCompose available. * Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tencent.compose.sample.mainpage.sectionItem import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.shape.CircleShape import androidx.compose.material.Button import androidx.compose.material.Slider import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.runtime.withFrameNanos import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.shadow import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.onSizeChanged import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import kotlin.random.Random @Composable internal fun FallingBalls() { val game = remember { Game() } val density = LocalDensity.current Column { Text( "Catch balls!${if (game.finished) " Game over!" else ""}", fontSize = 20.sp, color = Color(218, 120, 91) ) Text( "Score: ${game.score} Time: ${game.elapsed / 1_000_000} Blocks: ${game.numBlocks.toInt()}", fontSize = 20.sp ) Row { if (!game.started) { Slider( value = game.numBlocks / 20f, onValueChange = { game.numBlocks = (it * 20f).coerceAtLeast(1f) }, modifier = Modifier.width(250.dp) ) } Button( onClick = { game.started = !game.started if (game.started) { game.start() } } ) { Text(if (game.started) "Stop" else "Start", fontSize = 25.sp) } } if (game.started) { Box(modifier = Modifier.height(20.dp)) Box( modifier = Modifier .fillMaxWidth() .fillMaxHeight(1f) .onSizeChanged { with(density) { game.width = it.width.toDp() game.height = it.height.toDp() } } ) { game.pieces.forEachIndexed { index, piece -> Piece(index, piece) } } } LaunchedEffect(Unit) { while (true) { var previousTimeNanos = withFrameNanos { it } withFrameNanos { if (game.started && !game.paused && !game.finished) { game.update((it - previousTimeNanos).coerceAtLeast(0)) previousTimeNanos = it } } } } } } @Composable internal fun Piece(index: Int, piece: PieceData) { val boxSize = 40.dp Box( Modifier .offset(boxSize * index * 5 / 3, piece.position.dp) .shadow(30.dp) .clip(CircleShape) ) { Box( Modifier .size(boxSize, boxSize) .background(if (piece.clicked) Color.Gray else piece.color) .clickable(onClick = { piece.click() }) ) } } data class PieceData(val game: Game, val velocity: Float, val color: Color) { var clicked by mutableStateOf(false) var position by mutableStateOf(0f) fun update(dt: Long) { if (clicked) return val delta = (dt / 1E8 * velocity).toFloat() position = if (position < game.height.value) position + delta else 0f } fun click() { if (!clicked && !game.paused) { clicked = true game.clicked(this) } } } class Game { private val colors = arrayOf( Color.Red, Color.Blue, Color.Cyan, Color.Magenta, Color.Yellow, Color.Black ) var width by mutableStateOf(0.dp) var height by mutableStateOf(0.dp) var pieces = mutableStateListOf<PieceData>() private set var elapsed by mutableStateOf(0L) var score by mutableStateOf(0) private var clicked by mutableStateOf(0) var started by mutableStateOf(false) var paused by mutableStateOf(false) var finished by mutableStateOf(false) var numBlocks by mutableStateOf(5f) fun start() { clicked = 0 started = true finished = false paused = false pieces.clear() repeat(numBlocks.toInt()) { index -> pieces.add( PieceData( this, index * 1.5f + 5f, colors[index % colors.size] ).also { piece -> piece.position = Random.nextDouble(0.0, 100.0).toFloat() }) } } fun update(deltaTimeNanos: Long) { elapsed += deltaTimeNanos pieces.forEach { it.update(deltaTimeNanos) } } fun clicked(piece: PieceData) { score += piece.velocity.toInt() clicked++ if (clicked == numBlocks.toInt()) { finished = true } } }
2201_76010299/kmptpc_compose_sample
composeApp/src/commonMain/kotlin/com/tencent/compose/sample/mainpage/sectionItem/FallingBalls.kt
Kotlin
apache-2.0
6,620
/* * Tencent is pleased to support the open source community by making ovCompose available. * Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:Suppress("unused") package com.tencent.compose.sample.mainpage.sectionItem import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.clickable import androidx.compose.foundation.gestures.Orientation import androidx.compose.foundation.gestures.detectDragGestures import androidx.compose.foundation.gestures.detectTapGestures import androidx.compose.foundation.gestures.draggable import androidx.compose.foundation.gestures.rememberDraggableState import androidx.compose.foundation.gestures.rememberScrollableState import androidx.compose.foundation.gestures.rememberTransformableState import androidx.compose.foundation.gestures.scrollable import androidx.compose.foundation.gestures.transformable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material.ExperimentalMaterialApi import androidx.compose.material.FractionalThreshold import androidx.compose.material.Text import androidx.compose.material.rememberSwipeableState import androidx.compose.material.swipeable import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.dp import org.jetbrains.compose.ui.tooling.preview.Preview import kotlin.math.roundToInt @Composable internal fun GestureDemo() { Column { DraggableText() DraggableTextLowLevel() } } @Composable internal fun NestedScrollDemo() { AutomaticNestedScroll() } @Preview // [START android_compose_touchinput_gestures_clickable] @Composable private fun ClickableSample() { val count = remember { mutableStateOf(0) } // content that you want to make clickable Text( text = count.value.toString(), modifier = Modifier.clickable { count.value += 1 } ) } // [END android_compose_touchinput_gestures_clickable] @Preview @Composable private fun WithPointerInput() { val count = remember { mutableStateOf(0) } // content that you want to make clickable Text( text = count.value.toString(), modifier = // [START android_compose_touchinput_gestures_pointerinput] Modifier.pointerInput(Unit) { detectTapGestures( onPress = {}, onDoubleTap = {}, onLongPress = {}, onTap = {} ) } // [END android_compose_touchinput_gestures_pointerinput] ) } @Preview // [START android_compose_touchinput_gestures_vertical_scroll] @Composable private fun ScrollBoxes() { Column( modifier = Modifier .background(Color.LightGray) .size(100.dp) .verticalScroll(rememberScrollState()) ) { repeat(10) { Text("Item $it", modifier = Modifier.padding(2.dp)) } } } // [END android_compose_touchinput_gestures_vertical_scroll] @Preview // [START android_compose_touchinput_gestures_smooth_scroll] @Composable private fun ScrollBoxesSmooth() { // Smoothly scroll 100px on first composition val state = rememberScrollState() LaunchedEffect(Unit) { state.animateScrollTo(100) } Column( modifier = Modifier .background(Color.LightGray) .size(100.dp) .padding(horizontal = 8.dp) .verticalScroll(state) ) { repeat(10) { Text("Item $it", modifier = Modifier.padding(2.dp)) } } } // [END android_compose_touchinput_gestures_smooth_scroll] @Preview // [START android_compose_touchinput_gestures_scrollable] @Composable private fun ScrollableSample() { // actual composable state var offset by remember { mutableStateOf(0f) } Box( Modifier .size(150.dp) .scrollable( orientation = Orientation.Vertical, // Scrollable state: describes how to consume // scrolling delta and update offset state = rememberScrollableState { delta -> offset += delta delta } ) .background(Color.LightGray), contentAlignment = Alignment.Center ) { Text(offset.toString()) } } // [END android_compose_touchinput_gestures_scrollable] // [START android_compose_touchinput_gestures_nested_scroll] @Composable private fun AutomaticNestedScroll() { val gradient = Brush.verticalGradient(0f to Color.Gray, 1000f to Color.White) Box( modifier = Modifier // .background(Color.LightGray) .verticalScroll(rememberScrollState()) .padding(32.dp) ) { Column { repeat(6) { Box( modifier = Modifier .height(128.dp) .verticalScroll(rememberScrollState()) ) { Text( "Scroll here", modifier = Modifier .border(12.dp, Color.DarkGray) .background(brush = gradient) .padding(24.dp) .height(150.dp) ) } } } } } // [START android_compose_touchinput_gestures_draggable] @Composable private fun DraggableText() { var offsetX by remember { mutableStateOf(0f) } Text( modifier = Modifier .offset { IntOffset(offsetX.roundToInt(), 0) } .draggable( orientation = Orientation.Horizontal, state = rememberDraggableState { delta -> offsetX += delta } ), text = "Drag me!" ) } // [END android_compose_touchinput_gestures_draggable] // [START android_compose_touchinput_gestures_draggable_pointerinput] @Composable private fun DraggableTextLowLevel() { Box(modifier = Modifier.fillMaxSize()) { var offsetX by remember { mutableStateOf(0f) } var offsetY by remember { mutableStateOf(0f) } Box( Modifier .offset { IntOffset(offsetX.roundToInt(), offsetY.roundToInt()) } .background(Color.Blue) .size(50.dp) .pointerInput(Unit) { detectDragGestures { change, dragAmount -> change.consume() offsetX += dragAmount.x offsetY += dragAmount.y } } ) } } // [END android_compose_touchinput_gestures_draggable_pointerinput] // [START android_compose_touchinput_gestures_swipeable] @OptIn(ExperimentalMaterialApi::class) @Composable private fun SwipeableSample() { val width = 96.dp val squareSize = 48.dp val swipeableState = rememberSwipeableState(0) val sizePx = with(LocalDensity.current) { squareSize.toPx() } val anchors = mapOf(0f to 0, sizePx to 1) // Maps anchor points (in px) to states Box( modifier = Modifier .width(width) .swipeable( state = swipeableState, anchors = anchors, thresholds = { _, _ -> FractionalThreshold(0.3f) }, orientation = Orientation.Horizontal ) .background(Color.LightGray) ) { Box( Modifier .offset { IntOffset(swipeableState.offset.value.roundToInt(), 0) } .size(squareSize) .background(Color.DarkGray) ) } } // [END android_compose_touchinput_gestures_swipeable] // [START android_compose_touchinput_gestures_transformable] @Composable private fun TransformableSample() { // set up all transformation states var scale by remember { mutableStateOf(1f) } var rotation by remember { mutableStateOf(0f) } var offset by remember { mutableStateOf(Offset.Zero) } val state = rememberTransformableState { zoomChange, offsetChange, rotationChange -> scale *= zoomChange rotation += rotationChange offset += offsetChange } Box( Modifier // apply other transformations like rotation and zoom // on the pizza slice emoji .graphicsLayer( scaleX = scale, scaleY = scale, rotationZ = rotation, translationX = offset.x, translationY = offset.y ) // add transformable to listen to multitouch transformation events // after offset .transformable(state = state) .background(Color.Blue) .fillMaxSize() ) } // [END android_compose_touchinput_gestures_transformable]
2201_76010299/kmptpc_compose_sample
composeApp/src/commonMain/kotlin/com/tencent/compose/sample/mainpage/sectionItem/GesturesSnippets.kt
Kotlin
apache-2.0
10,550
/* * Tencent is pleased to support the open source community by making ovCompose available. * Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tencent.compose.sample.mainpage.sectionItem import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.verticalScroll import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.RectangleShape import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.graphics.painter.Painter import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.unit.dp import com.tencent.compose.sample.rememberLocalImage import composesample.composeapp.generated.resources.Res import composesample.composeapp.generated.resources.image_cat import org.jetbrains.compose.resources.ExperimentalResourceApi @OptIn(ExperimentalResourceApi::class) @Composable internal fun SimpleImage() { // Column { Column(modifier = Modifier.verticalScroll(rememberScrollState()).fillMaxWidth()) { Spacer(modifier = Modifier.fillMaxWidth().height(1.dp).background(Color.Red)) val contentScaleOptions = listOf( "ContentScale.Crop" to ContentScale.Crop, // 1 "ContentScale.Fit" to ContentScale.Fit, // 2 "ContentScale.FillBounds" to ContentScale.FillBounds, // 3 "ContentScale.FillWidth" to ContentScale.FillWidth, // 4 "ContentScale.FillHeight" to ContentScale.FillHeight, // 5 "ContentScale.Inside" to ContentScale.Inside, // 6 "ContentScale.None" to ContentScale.None // 7 ) val alignmentsList = listOf( listOf(Alignment.TopCenter, Alignment.TopEnd, Alignment.BottomStart), // 1 listOf(Alignment.CenterStart, Alignment.Center, Alignment.BottomEnd), // 2 listOf(Alignment.TopStart, Alignment.BottomCenter, Alignment.BottomStart), // 3 listOf(Alignment.TopStart, Alignment.CenterStart, Alignment.BottomStart), // 4 listOf(Alignment.CenterStart, Alignment.Center, Alignment.BottomEnd), // 5 listOf(Alignment.TopStart, Alignment.BottomCenter, Alignment.BottomStart), // 6 listOf(Alignment.TopCenter, Alignment.TopEnd, Alignment.BottomStart), // 7 ) val clips = listOf( CircleShape ) for ((index, pair) in contentScaleOptions.withIndex()) { val (title, scale) = pair val clipShape = clips.getOrNull(index) Text(title) Row(modifier = Modifier.fillMaxWidth()) { val customAlignments = alignmentsList[index] for (alignment in customAlignments) { Image( bitmap = rememberLocalImage(Res.drawable.image_cat), contentDescription = null, alignment = alignment, contentScale = scale, modifier = Modifier .size(100.dp) .background(Color.Yellow) .padding(1.dp) .graphicsLayer( shape = clipShape ?: RectangleShape, clip = clipShape != null ) ) } } } } }
2201_76010299/kmptpc_compose_sample
composeApp/src/commonMain/kotlin/com/tencent/compose/sample/mainpage/sectionItem/Image.kt
Kotlin
apache-2.0
4,619
package com.tencent.compose.sample.mainpage.sectionItem import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.layout.LazyLayoutItemProvider import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.Placeable import androidx.compose.ui.layout.SubcomposeLayout import androidx.compose.ui.unit.Constraints import androidx.compose.ui.unit.dp import org.jetbrains.compose.ui.tooling.preview.Preview @OptIn(ExperimentalFoundationApi::class) @Preview @Composable internal fun LazyLayoutDemo() { val items = remember { (0..100).toList().map { it.toString() } } val itemProvider = remember { object : LazyLayoutItemProvider { override val itemCount: Int get() = items.size @Composable override fun Item(index: Int, key: Any) { Box( modifier = Modifier .width(100.dp) .height(100.dp) .background(color = if (index % 2 == 0) Color.Red else Color.Green) ) { Text(text = items[index]) } } } } // 记录水平滚动偏移量 var scrollOffset by remember { mutableStateOf(0) } SubcomposeLayout(modifier = Modifier.size(500.dp)) { constraints -> val placeablesCache = mutableListOf<Pair<Placeable, Int>>() fun Placeable.mainAxisSize() = this.width fun Placeable.crossAxisSize() = this.height val childConstraints = Constraints(maxWidth = Constraints.Infinity, maxHeight = constraints.maxHeight) var currentItemIndex = 0 var crossAxisSize = 0 var mainAxisSize = 0 // 测量所有子项(移除宽度限制条件,确保100个子项都被测量) while (currentItemIndex < itemProvider.itemCount) { val itemPlaceable = subcompose(currentItemIndex) { itemProvider.Item(currentItemIndex, currentItemIndex) }.first().measure(childConstraints) placeablesCache.add(itemPlaceable to mainAxisSize) mainAxisSize += itemPlaceable.mainAxisSize() crossAxisSize = maxOf(crossAxisSize, itemPlaceable.crossAxisSize()) currentItemIndex++ } val layoutWidth = mainAxisSize val layoutHeight = crossAxisSize layout(layoutWidth, layoutHeight) { // 基于滚动偏移量放置子项 for ((placeable, position) in placeablesCache) { placeable.place(position - scrollOffset, 0) } } } Row( modifier = Modifier .fillMaxWidth() ) { // 左侧按钮:居左显示 Box(modifier = Modifier.size(200.dp)) { Text( text = "点击增加偏移", modifier = Modifier .background(Color.White) .clickable { scrollOffset += 100 } ) } // 右侧按钮:居右显示 Box(modifier = Modifier.size(200.dp)) { Text( text = "点击减少偏移", modifier = Modifier .background(Color.White) .clickable { scrollOffset -= 100 } ) } } }
2201_76010299/kmptpc_compose_sample
composeApp/src/commonMain/kotlin/com/tencent/compose/sample/mainpage/sectionItem/LazyLayout.kt
Kotlin
apache-2.0
4,017
package com.tencent.compose.sample.mainpage.sectionItem import androidx.compose.foundation.background import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyRow import androidx.compose.foundation.lazy.items import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import org.jetbrains.compose.ui.tooling.preview.Preview @Preview() @Composable internal fun LazyRowDemo() { val itemsList = (0..100).toList() val itemsIndexedList = listOf("A", "B", "C") // 水平滚动列表(LazyRow) LazyRow( modifier = Modifier .background(Color.LightGray.copy(alpha = 0.2f)) .padding(16.dp), // 列表项之间的间距(关键:避免文字挤在一起) horizontalArrangement = androidx.compose.foundation.layout.Arrangement.spacedBy(12.dp) ) { // 1. 渲染第一个列表(itemsList:0-5) items(itemsList) { number -> Text( text = "Item is $number", fontSize = 16.sp, // 文字大小 color = Color.Black ) } // 2. 渲染单个列表项(分隔用) item { Text( text = "Single item", fontSize = 16.sp, color = Color.Red ) } // 3. 渲染带索引的列表(itemsIndexedList:A/B/C) itemsIndexed(itemsIndexedList) { index, letter -> Text( text = "Index $index: $letter", fontSize = 16.sp, color = Color.Blue ) } } }
2201_76010299/kmptpc_compose_sample
composeApp/src/commonMain/kotlin/com/tencent/compose/sample/mainpage/sectionItem/LazyRow.kt
Kotlin
apache-2.0
1,847
// AppTabScreen.kt package com.tencent.compose.sample import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.CircleShape import androidx.compose.material.MaterialTheme import androidx.compose.material.Surface import androidx.compose.material.Text import androidx.compose.runtime.* // remember, mutableStateOf import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp /** * Compose implementation of AppTabPage (simplified). * * - AppHomeScreen is used for tab 0. * - Other tabs show AppEmptyScreen (with title). * - Icons are simple placeholder circles with the icon name as text. * * Replace placeholder image drawing with your own image loader (painterResource, AsyncImage, etc). */ /** Empty page shown for non-home tabs. */ @Composable internal fun AppEmptyScreen(title: String) { Surface(modifier = Modifier.fillMaxSize(), color = MaterialTheme.colors.background) { Box(contentAlignment = Alignment.Center) { Column(horizontalAlignment = Alignment.CenterHorizontally) { Text(text = title, fontSize = 24.sp, color = MaterialTheme.colors.onBackground) Spacer(modifier = Modifier.height(6.dp)) Text(text = "Placeholder content", color = MaterialTheme.colors.onBackground.copy(alpha = 0.7f)) } } } } @Composable internal fun AppTabScreen( titles: List<String> = listOf("Home", "Video", "Discover", "Message", "Me"), icons: List<String> = listOf("home", "video", "discover", "msg", "me"), initialSelectedIndex: Int = 0, tabBarHeightDp: Int = 80, onTabSelected: ((index: Int) -> Unit)? = null ) { var selectedIndex by remember { mutableStateOf(initialSelectedIndex.coerceIn(0, titles.size - 1)) } val bgColor = MaterialTheme.colors.background val tabBackground = MaterialTheme.colors.surface val textFocused = MaterialTheme.colors.primary val textUnfocused = MaterialTheme.colors.onSurface Column(modifier = Modifier.fillMaxSize().background(bgColor)) { Spacer(modifier = Modifier.height(0.dp)) Box(modifier = Modifier .weight(1f) .fillMaxSize() ) { when (selectedIndex) { 0 -> AppHomePreview() else -> AppEmptyScreen(title = titles.getOrNull(selectedIndex) ?: "Page ${selectedIndex + 1}") } } Row( modifier = Modifier .height(tabBarHeightDp.dp) .fillMaxSize() .background(tabBackground), horizontalArrangement = Arrangement.SpaceEvenly, verticalAlignment = Alignment.CenterVertically ) { val count = titles.size.coerceAtLeast(icons.size) for (i in 0 until count) { val title = titles.getOrNull(i) ?: "Tab $i" val iconName = icons.getOrNull(i) ?: title.lowercase() Column( horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center, modifier = Modifier .weight(1f) .clickable { selectedIndex = i onTabSelected?.invoke(i) } .padding(vertical = 6.dp) ) { PlaceholderIcon( text = iconName, isSelected = (i == selectedIndex), sizeDp = 30 ) Spacer(modifier = Modifier.height(6.dp)) Text( text = title, fontSize = 12.sp, color = if (i == selectedIndex) textFocused else textUnfocused, textAlign = TextAlign.Center ) } } } } } @Composable private fun PlaceholderIcon(text: String, isSelected: Boolean, sizeDp: Int = 30) { val bg = if (isSelected) MaterialTheme.colors.primary else MaterialTheme.colors.onSurface.copy(alpha = 0.08f) val fg = if (isSelected) Color.White else MaterialTheme.colors.onSurface Box( modifier = Modifier .size(sizeDp.dp) .clip(CircleShape) .background(bg), contentAlignment = Alignment.Center ) { Text( text = text.take(2).uppercase(), color = fg, fontSize = 12.sp, textAlign = TextAlign.Center ) } } @Composable internal fun AppHomeScreen() { Surface(modifier = Modifier.fillMaxSize(), color = MaterialTheme.colors.background) { Column( modifier = Modifier .fillMaxSize() .padding(20.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center ) { Text("App Home", fontSize = 28.sp, color = MaterialTheme.colors.primary) Spacer(modifier = Modifier.height(8.dp)) Text( "This is the placeholder for the original AppHomePage.\nReplace with your real Compose content.", textAlign = TextAlign.Center, color = MaterialTheme.colors.onBackground ) } } } @Composable internal fun PreviewAppTabScreen() { AppTabScreen() }
2201_76010299/kmptpc_compose_sample
composeApp/src/commonMain/kotlin/com/tencent/compose/sample/mainpage/sectionItem/PreviewAppTabScreen.kt
Kotlin
apache-2.0
6,146
/* * Tencent is pleased to support the open source community by making ovCompose available. * Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tencent.compose.sample.mainpage.sectionItem import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.material.Button import androidx.compose.material.CircularProgressIndicator import androidx.compose.material.LinearProgressIndicator import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import kotlinx.coroutines.delay import kotlinx.coroutines.launch import org.jetbrains.compose.ui.tooling.preview.Preview @Preview @Composable internal fun ProgressIndicatorExamples() { Column( modifier = Modifier .padding(48.dp) .fillMaxSize(), verticalArrangement = Arrangement.spacedBy(24.dp), horizontalAlignment = Alignment.CenterHorizontally, ) { Text("Determinate linear indicator:") LinearDeterminateIndicator() Text("Indeterminate linear indicator:") IndeterminateLinearIndicator() Text("Determinate circular indicator:") CircularDeterminateIndicator() Text("Indeterminate circular indicator:") IndeterminateCircularIndicator() } } @Preview // [START android_compose_components_determinateindicator] @Composable private fun LinearDeterminateIndicator() { var currentProgress by remember { mutableStateOf(0f) } var loading by remember { mutableStateOf(false) } val scope = rememberCoroutineScope() // Create a coroutine scope Column( verticalArrangement = Arrangement.spacedBy(12.dp), horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier.fillMaxWidth() ) { Button(onClick = { loading = true scope.launch { loadProgress { progress -> currentProgress = progress } loading = false // Reset loading when the coroutine finishes } }, enabled = !loading) { Text("Start loading") } if (loading) { LinearProgressIndicator( progress = currentProgress, modifier = Modifier.fillMaxWidth(), ) } } } /** Iterate the progress value */ private suspend fun loadProgress(updateProgress: (Float) -> Unit) { for (i in 1..100) { updateProgress(i.toFloat() / 100) delay(100) } } // [END android_compose_components_determinateindicator] @Preview @Composable private fun CircularDeterminateIndicator() { var currentProgress by remember { mutableStateOf(0f) } var loading by remember { mutableStateOf(false) } val scope = rememberCoroutineScope() // Create a coroutine scope Column( verticalArrangement = Arrangement.spacedBy(12.dp), horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier.fillMaxWidth() ) { Button(onClick = { loading = true scope.launch { loadProgress { progress -> currentProgress = progress } loading = false // Reset loading when the coroutine finishes } }, enabled = !loading) { Text("Start loading") } if (loading) { CircularProgressIndicator( progress = currentProgress, modifier = Modifier.width(64.dp), ) } } } @Preview @Composable private fun IndeterminateLinearIndicator() { var loading by remember { mutableStateOf(false) } Button(onClick = { loading = true }, enabled = !loading) { Text("Start loading") } if (!loading) return LinearProgressIndicator( modifier = Modifier.fillMaxWidth() ) } @Preview // [START android_compose_components_indeterminateindicator] @Composable private fun IndeterminateCircularIndicator() { var loading by remember { mutableStateOf(false) } Button(onClick = { loading = true }, enabled = !loading) { Text("Start loading") } if (!loading) return CircularProgressIndicator( modifier = Modifier.width(64.dp) ) } // [END android_compose_components_indeterminateindicator]
2201_76010299/kmptpc_compose_sample
composeApp/src/commonMain/kotlin/com/tencent/compose/sample/mainpage/sectionItem/ProgressIndicator.kt
Kotlin
apache-2.0
5,483
package com.tencent.compose.sample.mainpage.sectionItem import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.material.ExtendedFloatingActionButton import androidx.compose.material.FabPosition import androidx.compose.material.Icon import androidx.compose.material.IconButton import androidx.compose.material.Scaffold import androidx.compose.material.ScaffoldDefaults import androidx.compose.material.Text import androidx.compose.material.TopAppBar import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Menu import androidx.compose.material.rememberScaffoldState import androidx.compose.runtime.Composable import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.dp import kotlinx.coroutines.launch import org.jetbrains.compose.ui.tooling.preview.Preview @Preview @Composable internal fun ScaffoldDemo() { // Scaffold 状态管理器:控制侧边抽屉、Snackbar 等组件的展开/隐藏状态 val scaffoldState = rememberScaffoldState() // 协程作用域:用于执行 suspend 函数(如打开抽屉,需在协程中调用) val scope = rememberCoroutineScope() Scaffold( scaffoldState = scaffoldState, drawerContent = { Text("Drawer content") }, topBar = { TopAppBar( title = { Text("Simple Scaffold Screen") }, navigationIcon = { IconButton(onClick = { scope.launch { scaffoldState.drawerState.open() } }) { Icon( Icons.Filled.Menu, contentDescription = "Localized description" ) } }, ) }, floatingActionButtonPosition = FabPosition.End, floatingActionButton = { ExtendedFloatingActionButton( text = { Text("Inc") }, onClick = { /* fab click handler */ }, ) }, contentWindowInsets = ScaffoldDefaults.contentWindowInsets, content = { innerPadding -> // 懒加载列表:仅渲染可见项,优化大量数据展示的性能 LazyColumn(contentPadding = innerPadding) { items(count = 100) { Box(Modifier.fillMaxWidth().height(50.dp).background(Color.White)) } } }, ) }
2201_76010299/kmptpc_compose_sample
composeApp/src/commonMain/kotlin/com/tencent/compose/sample/mainpage/sectionItem/Scaffold.kt
Kotlin
apache-2.0
2,753
/* * Tencent is pleased to support the open source community by making ovCompose available. * Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tencent.compose.sample.mainpage.sectionItem import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.material.ExperimentalMaterialApi import androidx.compose.material.RangeSlider import androidx.compose.material.Slider import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableFloatStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.testTag import androidx.compose.ui.unit.dp import org.jetbrains.compose.ui.tooling.preview.Preview @Preview @Composable internal fun SliderExamples() { Column( modifier = Modifier .padding(16.dp) .fillMaxSize(), verticalArrangement = Arrangement.spacedBy(8.dp), horizontalAlignment = Alignment.CenterHorizontally, ) { Text("Minimal slider component") SliderMinimalExample() Text("Advanced slider component") SliderAdvancedExample() Text("Range slider component") RangeSliderExample() } } // [START android_compose_components_sliderminimal] @Preview @Composable private fun SliderMinimalExample() { var sliderPosition by remember { mutableFloatStateOf(0f) } Column { Slider( value = sliderPosition, onValueChange = { sliderPosition = it }, modifier = Modifier.testTag("minimalSlider"), ) Text(text = sliderPosition.toString()) } } // [END android_compose_components_sliderminimal] // [START android_compose_components_slideradvanced] @Preview @Composable private fun SliderAdvancedExample() { var sliderPosition by remember { mutableFloatStateOf(0f) } Column { Slider( value = sliderPosition, onValueChange = { sliderPosition = it }, steps = 3, valueRange = 0f..50f, modifier = Modifier.testTag("advancedSlider") ) Text(text = sliderPosition.toString()) } } // [END android_compose_components_slideradvanced] // [START android_compose_components_rangeslider] @OptIn(ExperimentalMaterialApi::class) @Preview @Composable internal fun RangeSliderExample() { var sliderPosition by remember { mutableStateOf(0f..100f) } Column { RangeSlider( value = sliderPosition, steps = 5, onValueChange = { range -> sliderPosition = range }, valueRange = 0f..100f, onValueChangeFinished = { // launch some business logic update with the state you hold // viewModel.updateSelectedSliderValue(sliderPosition) }, modifier = Modifier.testTag("rangeSlider") ) Text(text = sliderPosition.toString()) } } // [END android_compose_components_rangeslider]
2201_76010299/kmptpc_compose_sample
composeApp/src/commonMain/kotlin/com/tencent/compose/sample/mainpage/sectionItem/Slider.kt
Kotlin
apache-2.0
3,915
/* * Tencent is pleased to support the open source community by making ovCompose available. * Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tencent.compose.sample.mainpage.sectionItem import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.material.Switch import androidx.compose.material.SwitchDefaults import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.testTag import androidx.compose.ui.unit.dp import org.jetbrains.compose.ui.tooling.preview.Preview @Preview @Composable internal fun SwitchExamples() { Column( modifier = Modifier .padding(16.dp) .fillMaxSize(), verticalArrangement = Arrangement.spacedBy(8.dp), horizontalAlignment = Alignment.CenterHorizontally, ) { Text("Minimal switch component") SwitchMinimalExample() Text("Switch with label") SwitchWithLabelMinimalExample() Text("Switch with custom colors") SwitchWithCustomColors() } } @Preview // [START android_compose_components_switchminimal] @Composable private fun SwitchMinimalExample() { var checked by remember { mutableStateOf(true) } Switch( checked = checked, onCheckedChange = { checked = it }, modifier = Modifier.testTag("minimalSwitch") ) } // [END android_compose_components_switchminimal] @Preview // [START android_compose_components_switchwithlabel] @Composable private fun SwitchWithLabelMinimalExample() { var checked by remember { mutableStateOf(true) } Row( verticalAlignment = Alignment.CenterVertically ) { Text( modifier = Modifier.padding(8.dp), text = if (checked) "Checked" else "Unchecked", ) Switch( checked = checked, onCheckedChange = { checked = it }, modifier = Modifier.testTag("minimalLabelSwitch") ) } } // [END android_compose_components_switchwithlabel] @Preview // [START android_compose_components_switchwithcustomcolors] @Composable private fun SwitchWithCustomColors() { var checked by remember { mutableStateOf(true) } Switch( checked = checked, onCheckedChange = { checked = it }, modifier = Modifier.testTag("customSwitch"), colors = SwitchDefaults.colors( checkedThumbColor = Color(0.4f, 0.3137255f, 0.6431373f, 1.0f), checkedTrackColor = Color(0.91764706f, 0.8666667f, 1.0f, 1.0f), uncheckedThumbColor = Color(0.38431373f, 0.35686275f, 0.44313726f, 1.0f), uncheckedTrackColor = Color(0.9098039f, 0.87058824f, 0.972549f, 1.0f), ) ) } // [END android_compose_components_switchwithcustomcolors]
2201_76010299/kmptpc_compose_sample
composeApp/src/commonMain/kotlin/com/tencent/compose/sample/mainpage/sectionItem/Switch.kt
Kotlin
apache-2.0
3,903
package com.tencent.compose.sample.mainpage.sectionItem import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.material.MaterialTheme import androidx.compose.material.Tab import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.dp import org.jetbrains.compose.ui.tooling.preview.Preview @Preview() @Composable internal fun TabDemo() { // 记住选中状态,实现交互效果 var isSelected by remember { mutableStateOf(false) } // 可配置的标题文本 val tabTitle = "标签页" // 定义选中和未选中状态的颜色,便于统一修改 val indicatorColor = if (isSelected) Color.Red else Color.Transparent val textColor = if (isSelected) { MaterialTheme.colors.primary } else { MaterialTheme.colors.onSurface.copy(alpha = 0.6f) } Tab( selected = isSelected, onClick = { isSelected = !isSelected }, modifier = Modifier .height(50.dp) ) { Column( modifier = Modifier .fillMaxWidth() .padding(horizontal = 10.dp), verticalArrangement = Arrangement.SpaceBetween, horizontalAlignment = Alignment.CenterHorizontally ) { // 选中指示器 Box( modifier = Modifier .size(10.dp) .background(color = indicatorColor) ) // 标签文本 Text( text = tabTitle, style = MaterialTheme.typography.body1, color = textColor, ) } } }
2201_76010299/kmptpc_compose_sample
composeApp/src/commonMain/kotlin/com/tencent/compose/sample/mainpage/sectionItem/Tab.kt
Kotlin
apache-2.0
2,307
/* * Tencent is pleased to support the open source community by making ovCompose available. * Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tencent.compose.sample.mainpage.sectionItem import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.text.ClickableText import androidx.compose.material.LocalTextStyle import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.text.SpanStyle import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.buildAnnotatedString import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontStyle import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextDecoration import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.text.withStyle import androidx.compose.ui.unit.TextUnit import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp @Composable internal fun SimpleTextPage() { val textContent = "Compose Text 文本 & AnnotatedString 多种样式的文本的基本数据结构" LazyColumn(modifier = Modifier.fillMaxSize().fillMaxHeight()) { item { AnnotatedStringTextPage() } item { Text( text = "fontSize = 16.sp color = Red $textContent", color = Color.Red, fontSize = 16.sp ) Spacer(modifier = Modifier.fillMaxWidth().height(10.dp)) } item { Text( text = "fontSize = 18.sp color = Blue, $textContent", color = Color.Blue, fontSize = 18.sp ) Spacer(modifier = Modifier.fillMaxWidth().height(10.dp)) } item { Text( text = "FontWeight.Light, $textContent", fontWeight = FontWeight.Light ) Spacer(modifier = Modifier.fillMaxWidth().height(10.dp)) } item { Text( text = "FontWeight.Bold, $textContent", fontWeight = FontWeight.Bold ) Spacer(modifier = Modifier.fillMaxWidth().height(10.dp)) } item { Text( text = "FontWeight.Black, $textContent", fontWeight = FontWeight.Black ) Spacer(modifier = Modifier.fillMaxWidth().height(10.dp)) } item { Text( text = "FontFamily.Cursive, $textContent", fontFamily = FontFamily.Cursive ) Spacer(modifier = Modifier.fillMaxWidth().height(10.dp)) } item { Text( text = "FontFamily.Serif, $textContent", fontFamily = FontFamily.Serif ) Spacer(modifier = Modifier.fillMaxWidth().height(10.dp)) } item { Text( text = "letterSpacing = 4.sp, $textContent", letterSpacing = 4.sp ) Spacer(modifier = Modifier.fillMaxWidth().height(10.dp)) } item { Text( text = "TextDecoration.Underline, $textContent", textDecoration = TextDecoration.Underline ) Spacer(modifier = Modifier.fillMaxWidth().height(10.dp)) } item { Text( text = "TextDecoration.LineThrough, $textContent", textDecoration = TextDecoration.LineThrough ) Spacer(modifier = Modifier.fillMaxWidth().height(10.dp)) } item { Text( text = "TextAlign.Left, $textContent", textAlign = TextAlign.Left, ) Spacer(modifier = Modifier.fillMaxWidth().height(10.dp)) } item { Text( text = "TextAlign.Center, $textContent", textAlign = TextAlign.Center, ) Spacer(modifier = Modifier.fillMaxWidth().height(10.dp)) } item { Text( text = "TextAlign.Right, $textContent", textAlign = TextAlign.Right, ) Spacer(modifier = Modifier.fillMaxWidth().height(10.dp)) } item { Text( text = "TextAlign.Justify, $textContent", textAlign = TextAlign.Justify, ) Spacer(modifier = Modifier.fillMaxWidth().height(10.dp)) } item { Text( text = "lineHeight = 40.sp, $textContent", lineHeight = 40.sp, ) Spacer(modifier = Modifier.fillMaxWidth().height(10.dp)) } item { Text( text = "TextOverflow.Clip, $textContent", overflow = TextOverflow.Clip, ) Spacer(modifier = Modifier.fillMaxWidth().height(10.dp)) } item { Text( text = "softWrap = false, $textContent $textContent", softWrap = false, ) Spacer(modifier = Modifier.fillMaxWidth().height(10.dp)) } item { Text( text = "TextOverflow.Ellipsis, $textContent $textContent", overflow = TextOverflow.Ellipsis, ) Spacer(modifier = Modifier.fillMaxWidth().height(10.dp)) } item { Text( text = "style = background:Color.Gray, $textContent", style = TextStyle(background = Color.Gray) ) Spacer(modifier = Modifier.fillMaxWidth().height(10.dp)) } item { Text( text = "style = Brush.linearGradient, $textContent", style = TextStyle( brush = Brush.linearGradient( colors = listOf(Color.Red, Color.Blue) ), alpha = 0.8f ) ) Spacer(modifier = Modifier.fillMaxWidth().height(10.dp)) } } } @Composable private fun AnnotatedStringTextPage() { val annotatedString3 = buildAnnotatedString { withStyle(style = SpanStyle(fontWeight = FontWeight.Bold, color = Color.Blue)) { append("Compose Text ") } withStyle(style = SpanStyle()) { append("通过") } withStyle(style = SpanStyle(fontStyle = FontStyle.Italic, color = Color.Red)) { append(" AnnotatedString ") } withStyle(style = SpanStyle()) { append("设置富文本效果!") } withStyle(style = SpanStyle(color = Color.Red)) { append("点击 www.qq.com") } addStringAnnotation( tag = "URL", annotation = "https://v.qq.com", start = 40, end = 55 ) } Column(modifier = Modifier.fillMaxSize()) { Text(text = annotatedString3, modifier = Modifier.clickable { annotatedString3.getStringAnnotations("URL", 7, 14) .firstOrNull()?.let { it -> println("jump to v.qq.com $it") } }) ClickableText( text = AnnotatedString("ClickableText ") + annotatedString3, onClick = { integer -> annotatedString3.getStringAnnotations("URL", integer, integer).firstOrNull()?.let { println("jump to v.qq.com $it") } }) } }
2201_76010299/kmptpc_compose_sample
composeApp/src/commonMain/kotlin/com/tencent/compose/sample/mainpage/sectionItem/Text.kt
Kotlin
apache-2.0
8,778
/* * Tencent is pleased to support the open source community by making ovCompose available. * Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tencent.compose.sample.mainpage.sectionItem import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material.Button import androidx.compose.material.Text import androidx.compose.material.TextField import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalFocusManager import androidx.compose.ui.platform.LocalSoftwareKeyboardController import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.input.KeyboardType @Composable internal fun TextField2() { var username by remember { mutableStateOf("") } var password by remember { mutableStateOf("") } var age by remember { mutableStateOf("") } var email by remember { mutableStateOf("") } Column(modifier = Modifier.fillMaxWidth()) { Text("用户名") TextField( value = username, placeholder = { Text("请输入用户名") }, keyboardOptions = KeyboardOptions( keyboardType = KeyboardType.Phone, imeAction = ImeAction.Next ), onValueChange = { username = it }, modifier = Modifier.fillMaxWidth() ) Text("密码") TextField( value = password, placeholder = { Text("请输入密码") }, keyboardOptions = KeyboardOptions( keyboardType = KeyboardType.NumberPassword, imeAction = ImeAction.Next ), onValueChange = { password = it }, modifier = Modifier.fillMaxWidth() ) Text("年龄") TextField( value = age, placeholder = { Text("请输入年龄") }, keyboardOptions = KeyboardOptions( keyboardType = KeyboardType.Number, imeAction = ImeAction.Next ), onValueChange = { age = it }, modifier = Modifier.fillMaxWidth() ) Text("邮箱") TextField( value = email, placeholder = { Text("请输入邮箱") }, keyboardOptions = KeyboardOptions( keyboardType = KeyboardType.Email, imeAction = ImeAction.Next ), onValueChange = { email = it }, modifier = Modifier.fillMaxWidth() ) val focusManager = LocalFocusManager.current Button(onClick = { focusManager.clearFocus() }, modifier = Modifier.fillMaxWidth()) { Text("注册") } DisposableEffect(Unit) { onDispose { focusManager.clearFocus() } } } }
2201_76010299/kmptpc_compose_sample
composeApp/src/commonMain/kotlin/com/tencent/compose/sample/mainpage/sectionItem/TextField2.kt
Kotlin
apache-2.0
3,880
/* * Tencent is pleased to support the open source community by making ovCompose available. * Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tencent.compose.sample.mainpage.sectionItem import androidx.compose.foundation.background import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material.Button import androidx.compose.material.Text import androidx.compose.material.TextField import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalFocusManager import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.unit.dp import androidx.compose.ui.window.Dialog @Composable internal fun TextField3() { var mobile by remember { mutableStateOf("") } var showDialog by remember { mutableStateOf(false) } if (showDialog) { Dialog( onDismissRequest = { showDialog = false }, content = { Column(Modifier.fillMaxWidth().background(Color.White).padding(30.dp)) { Text("手机号") TextField( value = mobile, placeholder = { Text("请输入手机号") }, keyboardOptions = KeyboardOptions( keyboardType = KeyboardType.Phone, imeAction = ImeAction.Next ), onValueChange = { mobile = it }, modifier = Modifier.fillMaxWidth() ) Button(onClick = {}, modifier = Modifier.fillMaxWidth()) { Text("注册") } } } ) } Column(Modifier.fillMaxWidth()) { Row { Button(onClick = { showDialog = true }, modifier = Modifier.padding(20.dp)) { Text("注册") } } } val focusManager = LocalFocusManager.current DisposableEffect(Unit) { onDispose { focusManager.clearFocus() } } }
2201_76010299/kmptpc_compose_sample
composeApp/src/commonMain/kotlin/com/tencent/compose/sample/mainpage/sectionItem/TextField3.kt
Kotlin
apache-2.0
3,288
package com.tencent.compose.sample.mainpage.sectionItem import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.material.AppBarDefaults import androidx.compose.material.DrawerValue import androidx.compose.material.Icon import androidx.compose.material.IconButton import androidx.compose.material.Scaffold import androidx.compose.material.Text import androidx.compose.material.TopAppBar import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Favorite import androidx.compose.material.icons.filled.Menu import androidx.compose.material.icons.filled.MoreVert import androidx.compose.material.rememberDrawerState import androidx.compose.material.rememberScaffoldState import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import kotlinx.coroutines.launch import org.jetbrains.compose.ui.tooling.preview.Preview @Preview() @Composable internal fun TopAppBarDemo() { // 1. 创建Scaffold状态管理对象,用于控制抽屉等组件状态 val scaffoldState = rememberScaffoldState( drawerState = rememberDrawerState(initialValue = DrawerValue.Closed) ) // 2. 创建协程作用域,用于处理需要在协程中执行的操作(如抽屉状态变更) val coroutineScope = rememberCoroutineScope() // 3. 状态管理:记录收藏按钮的选中状态 var isFavorite by remember { mutableStateOf(false) } // 使用Scaffold作为父容器,提供完整的页面结构 Scaffold( scaffoldState = scaffoldState, // 顶部导航栏配置 topBar = { TopAppBar( // 导航栏与系统窗口的边距设置,使用默认值适配状态栏 windowInsets = AppBarDefaults.topAppBarWindowInsets, // 导航栏标题 title = { Text( text = "顶部导航栏", fontSize = 18.sp, textAlign = TextAlign.Center, modifier = Modifier.fillMaxWidth() // 标题占满宽度实现居中 ) }, // 左侧导航图标区域 navigationIcon = { IconButton( onClick = { // 点击打开/关闭抽屉菜单 coroutineScope.launch { if (scaffoldState.drawerState.isOpen) { scaffoldState.drawerState.close() } else { scaffoldState.drawerState.open() } } } ) { Icon( imageVector = Icons.Filled.Menu, contentDescription = "打开侧边菜单", // 无障碍描述 tint = Color.White // 图标颜色 ) } }, // 右侧操作按钮区域 actions = { // 收藏按钮 IconButton( onClick = { isFavorite = !isFavorite }, // 切换收藏状态 ) { Icon( imageVector = Icons.Filled.Favorite, contentDescription = if (isFavorite) "取消收藏" else "添加收藏", tint = if (isFavorite) Color.Red else Color.White // 状态变色 ) } // 更多选项按钮 IconButton( onClick = { /* 打开更多操作菜单的逻辑 */ } ) { Icon( imageVector = Icons.Filled.MoreVert, // 更多选项图标 contentDescription = "更多操作", tint = Color.White ) } }, // 导航栏背景色 backgroundColor = Color(0xFF6200EE), // 导航栏阴影高度,增强层次感 elevation = 4.dp ) }, // 抽屉菜单内容 drawerContent = { Text( text = "侧边抽屉菜单", modifier = Modifier.padding(16.dp) ) } ) { innerPadding -> // 主内容区域,使用innerPadding避免被导航栏遮挡 Text( text = "主页面内容", modifier = Modifier .padding(innerPadding) .fillMaxWidth() .padding(16.dp) ) } }
2201_76010299/kmptpc_compose_sample
composeApp/src/commonMain/kotlin/com/tencent/compose/sample/mainpage/sectionItem/TopAppBar.kt
Kotlin
apache-2.0
5,299
package com.tencent.compose.sample.mainpage.sectionItem import androidx.compose.foundation.border import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.size import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.onGloballyPositioned import androidx.compose.ui.unit.dp import org.jetbrains.compose.resources.ExperimentalResourceApi @OptIn(ExperimentalResourceApi::class) @Composable internal fun composeView1500Page() { val loaded = remember { mutableStateOf(false) } Column( modifier = Modifier .verticalScroll(rememberScrollState()) .fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally ) { repeat(1500) { index -> Box( modifier = Modifier .size(300.dp, 100.dp) .border( width = 2.dp, color = Color.Red, ) .then( if (index == 1499) Modifier.onGloballyPositioned { loaded.value = true //trace_tag_end() } else Modifier ) ) { Text( text = "Item #$index", ) } } } if (loaded.value) { println("页面加载完成 ✅") } }
2201_76010299/kmptpc_compose_sample
composeApp/src/commonMain/kotlin/com/tencent/compose/sample/mainpage/sectionItem/compose1500view.kt
Kotlin
apache-2.0
1,880
/* * Tencent is pleased to support the open source community by making ovCompose available. * Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:Suppress("unused") package com.tencent.compose import androidx.compose.ui.uikit.OnFocusBehavior import androidx.compose.ui.uikit.RenderBackend import androidx.compose.ui.window.ComposeUIViewController import com.tencent.compose.sample.mainpage.MainPage import kotlin.experimental.ExperimentalObjCName @OptIn(ExperimentalObjCName::class) @ObjCName("MainViewController") fun MainViewController() = ComposeUIViewController( configure = { onFocusBehavior = OnFocusBehavior.DoNothing } ) { MainPage(false) } @OptIn(ExperimentalObjCName::class) @ObjCName("SkiaRenderViewController") fun SkiaRenderMainViewController() = ComposeUIViewController( configure = { onFocusBehavior = OnFocusBehavior.DoNothing renderBackend = RenderBackend.Skia } ) { MainPage(true) }
2201_76010299/kmptpc_compose_sample
composeApp/src/iosMain/kotlin/com/tencent/compose/MainViewController.kt
Kotlin
apache-2.0
1,537
/* * Tencent is pleased to support the open source community by making ovCompose available. * Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tencent.compose import platform.UIKit.UIDevice internal class IOSPlatform : Platform { override val name: String = UIDevice.currentDevice.systemName() + " " + UIDevice.currentDevice.systemVersion } internal actual fun getPlatform(): Platform = IOSPlatform()
2201_76010299/kmptpc_compose_sample
composeApp/src/iosMain/kotlin/com/tencent/compose/Platform.ios.kt
Kotlin
apache-2.0
1,020
/* * Tencent is pleased to support the open source community by making ovCompose available. * Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tencent.compose.sample import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.MutableState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.graphics.ImageBitmap import androidx.compose.ui.graphics.UikitImageBitmap import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.IO import kotlinx.coroutines.withContext import org.jetbrains.compose.resources.DrawableResource import org.jetbrains.compose.resources.ExperimentalResourceApi import platform.Foundation.NSBundle import platform.UIKit.UIImage private val emptyImageBitmap: ImageBitmap by lazy { ImageBitmap(1, 1) } private val imageFolderPath:String by lazy { "${NSBundle.mainBundle().bundlePath}/compose-resources/" } @OptIn(ExperimentalResourceApi::class) @Composable actual fun rememberLocalImage(id: DrawableResource): ImageBitmap { var imageBitmap: ImageBitmap by remember { mutableStateOf(emptyImageBitmap) } LaunchedEffect(Unit) { withContext(Dispatchers.IO) { val imagePath = "$imageFolderPath/${id.resourceItemPath()}" val image = UIImage.imageNamed(imagePath) ?: return@withContext imageBitmap = UikitImageBitmap(image) } } return imageBitmap }
2201_76010299/kmptpc_compose_sample
composeApp/src/iosMain/kotlin/com/tencent/compose/sample/Images.ios.kt
Kotlin
apache-2.0
2,150
/* * Tencent is pleased to support the open source community by making ovCompose available. * Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tencent.compose.sample import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.width import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.interop.UIKitView2 import androidx.compose.ui.unit.dp import kotlinx.cinterop.ExperimentalForeignApi @OptIn(ExperimentalForeignApi::class) @Composable internal fun Vertical2Vertical() { Box(Modifier.fillMaxSize(), contentAlignment = Alignment.TopCenter) { val scrollState = rememberScrollState() Column { Text( "Compose 不可滚动区域顶部", Modifier.fillMaxWidth().height(40.dp).background(Color.Yellow) ) Column( Modifier.fillMaxWidth().background(Color.LightGray).height(300.dp) .verticalScroll(scrollState), horizontalAlignment = Alignment.CenterHorizontally ) { Text( "Compose 可滚动区域顶部", Modifier.fillMaxWidth().height(80.dp).background(Color.Cyan) ) UIKitView2( factory = { allocObject("ComposeSample.ImagesScrollView") }, modifier = Modifier.width(260.dp).height(440.dp) ) Text( "Compose 可滚动区域底部", Modifier.fillMaxWidth().height(80.dp).background(Color.Cyan) ) } Text( "Compose 不可滚动区域底部", color = Color.White, modifier = Modifier.fillMaxWidth().height(40.dp).background(Color.Blue) ) } } }
2201_76010299/kmptpc_compose_sample
composeApp/src/iosMain/kotlin/com/tencent/compose/sample/Vectical2Vectical.kt
Kotlin
apache-2.0
3,001
/* * Tencent is pleased to support the open source community by making ovCompose available. * Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tencent.compose.sample import kotlinx.cinterop.ExperimentalForeignApi import platform.Foundation.CFBridgingRelease import platform.Foundation.CFBridgingRetain import platform.Foundation.NSClassFromString import platform.Foundation.NSSelectorFromString import platform.darwin.NSObject @OptIn(ExperimentalForeignApi::class) internal inline fun <reified T> allocObject(className: String): T { val cls = NSClassFromString(className) as NSObject val obj = cls.performSelector(NSSelectorFromString("new")) as T val cfObj = CFBridgingRetain(obj) CFBridgingRelease(cfObj) CFBridgingRelease(cfObj) return obj }
2201_76010299/kmptpc_compose_sample
composeApp/src/iosMain/kotlin/com/tencent/compose/sample/allocObject.kt
Kotlin
apache-2.0
1,375
/* * Tencent is pleased to support the open source community by making ovCompose available. * Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tencent.compose.sample.backhandler import androidx.compose.runtime.Composable @Composable actual fun BackHandler(enable: Boolean, onBack: () -> Unit) { }
2201_76010299/kmptpc_compose_sample
composeApp/src/iosMain/kotlin/com/tencent/compose/sample/backhandler/BackHandler.ios.kt
Kotlin
apache-2.0
903