You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Xamarin(C#)中LinearLayout无法显示图片问题求助

Xamarin卡牌图片不显示问题排查与解决

问题描述

使用Xamarin开发功能:根据用户输入的数字展示对应数量的卡牌图片,编译和运行阶段无报错,但图片始终无法显示。图片命名规则为img{1-13的数字}{'S','H','D','C'}(例如img1S、img7H)。

相关代码

图片显示逻辑代码

private void ShowBtn_Click(object sender, EventArgs e)
{
        main.RemoveAllViews();
        int imgToShow = int.Parse(editTxt.Text);
        char[] types = { 'S', 'C', 'H', 'D' };
        LinearLayout layout = new LinearLayout(this);

        for (int i = 0; i < imgToShow; i++)
        {
            if (i % 5 == 0)
            {
                main.AddView(layout);
                layout = new LinearLayout(this);
                continue;
            }

            // add image
            var imgv = new ImageView(this);
            imgv.SetImageResource(Resources.GetIdentifier($"img{rnd.Next(1, 14)}{types[rnd.Next(4)]}", "drawable", this.PackageName));
            imgv.LayoutParameters = new LinearLayout.LayoutParams(0, 200, 1);
            layout.AddView(imgv);
        }

        main.AddView(layout);
}

控件初始化代码

void Init()
{
        main = FindViewById<LinearLayout>(Resource.Id.mainLayout);
        closeBtn = FindViewById<Button>(Resource.Id.close);
        showBtn = FindViewById<Button>(Resource.Id.show);
        clsBtn = FindViewById<Button>(Resource.Id.cls);
        editTxt = FindViewById<EditText>(Resource.Id.editTxt);
}

布局XML代码

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <TextView
            android:layout_width="220dp"
            android:layout_height="50dp"
            android:text="Cards to reveal"
            android:textSize="30sp"/>
        <EditText
            android:layout_width="150dp"
            android:layout_height="match_parent"
            android:inputType="number"
            android:id="@+id/editTxt"/>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:orientation="horizontal">
        <Button
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:layout_margin="5dp"
            android:text="Show Images"
            android:textSize="13sp"
            android:id="@+id/show"/>
        <Button
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:layout_margin="5dp"
            android:text="Clear"
            android:textSize="13sp"
            android:id="@+id/cls"/>
        <Button
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:layout_margin="5dp"
            android:text="Close"
            android:textSize="13sp"
            android:id="@+id/close"/>

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:id="@+id/mainLayout"/>

</LinearLayout>

排查与解决步骤

1. 检查图片资源配置

  • 确认图片文件放置在Resources/drawable目录(若区分分辨率,可放在对应drawable-xxxhdpi等目录,通用资源放drawable即可)
  • 在Visual Studio中选中图片文件,右键打开属性面板:
    • 设置Build Action为AndroidResource
    • 设置Copy to Output Directory为Do not copy(Xamarin会自动打包资源)

2. 验证资源ID获取正确性

Resources.GetIdentifier返回0代表找不到对应资源,建议添加日志或断点验证:

var imgName = $"img{rnd.Next(1,14)}{types[rnd.Next(4)]}";
var resId = Resources.GetIdentifier(imgName, "drawable", PackageName);
if (resId == 0)
{
    System.Diagnostics.Debug.WriteLine($"未找到资源: {imgName}");
    continue;
}
imgv.SetImageResource(resId);

3. 修复循环布局逻辑

当前循环会先添加空布局,导致第一行无图片,且未设置横向排列,调整逻辑:

private void ShowBtn_Click(object sender, EventArgs e)
{
        main.RemoveAllViews();
        int imgToShow = int.Parse(editTxt.Text);
        char[] types = { 'S', 'C', 'H', 'D' };
        LinearLayout layout = new LinearLayout(this);
        layout.Orientation = Orientation.Horizontal; // 强制横向排列

        for (int i = 0; i < imgToShow; i++)
        {
            var imgv = new ImageView(this);
            var imgName = $"img{rnd.Next(1,14)}{types[rnd.Next(4)]}";
            var resId = Resources.GetIdentifier(imgName, "drawable", PackageName);
            if (resId == 0)
            {
                System.Diagnostics.Debug.WriteLine($"未找到资源: {imgName}");
                continue;
            }
            imgv.SetImageResource(resId);
            
            // 转换dp为像素,避免不同设备显示异常
            int heightInDp = 100;
            int heightInPx = (int)TypedValue.ApplyDimension(ComplexUnitType.Dip, heightInDp, Resources.DisplayMetrics);
            imgv.LayoutParameters = new LinearLayout.LayoutParams(0, heightInPx, 1);
            
            layout.AddView(imgv);

            // 每5张图片换行
            if ((i + 1) % 5 == 0)
            {
                main.AddView(layout);
                layout = new LinearLayout(this);
                layout.Orientation = Orientation.Horizontal;
            }
        }

        // 添加最后一行剩余图片
        if (layout.ChildCount > 0)
        {
            main.AddView(layout);
        }
}

4. 确认随机数实例初始化

确保rnd是类级别的Random实例,避免循环内重复初始化导致随机数重复:

private Random rnd = new Random();

内容的提问来源于stack exchange,提问作者Maxim Zyuryaev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 20:13:17