0

我的游戏需要在每个 onCreate 类中更新 TextView 的背景以显示玩家的健康状况,但是目前我能想到的唯一方法是这样

int Health = 100;

    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_act1);

    if (Health == 100){
        HealthDisplay.setBackgroundResource(R.drawable.health100);
    } else if (Health == 99){
        HealthDisplay.setBackgroundResource(R.drawable.health99);
    } else if (Health == 98){
        HealthDisplay.setBackgroundResource(R.drawable.health98);
    } else if (Health == 99){
        HealthDisplay.setBackgroundResource(R.drawable.health98);
    } else if (Health == 99){
        HealthDisplay.setBackgroundResource(R.drawable.health98);
    } else if (Health == 99){
        HealthDisplay.setBackgroundResource(R.drawable.health98);
    }

etc.
}

必须有一种更简单/更快的方法来做到这一点,特别是因为我也需要对其他两个统计数据做类似的事情。

我曾考虑让一个单独的类处理它,并在 onCreate 中有一两行告诉它运行该类以更新背景图像,然后返回到这个。

或者,也许这样的事情是可能的?

int Health = 100;

HealthDisplay.setBackgroundResource(R.drawable.health(Health));
4

3 回答 3

0

“我的游戏需要在每个 onCreate 类中更新一个 TextView 的背景,以显示玩家的健康状况”

对不起,我不明白。如果您想在运行时更新背景,请不要在 onCreate 中执行此操作,因为它只被调用一次(在创建活动时)。

只需通过在 TextView 上调用 setBackgroundResource 创建一个将更新此背景的方法。

于 2013-01-22T14:57:26.797 回答
0

我的建议是拥有一张图像(为了完全健康),每次裁剪它并根据您的健康水平显示它的百分比。例如:

private ImageView healthLevel;
private ClipDrawable clipDrawable;
    @Override
        public void onCreate(Bundle savedInstanceState) {
            healthLevel = (ImageView ) findViewById(R.id.health);   //there a corresponding ImageView in the layout
            BitmapDrawable bitmapDrawable = new BitmapDrawable(BitmapFactory.decodeResource(getResources(),    R.drawable.full_health));
            //vertical bar cropped from top
            clipDrawable = new ClipDrawable(bitmapDrawable, Gravity.BOTTOM, ClipDrawable.VERTICAL);  
            healthLevel.setImageDrawable(clipDrawable);
    }

然后在另一个线程中你会调用:

int health = 54;
clipDrawable.setLevel(health);
clipDrawable.invalidateSelf();
于 2013-01-22T15:16:08.850 回答
0

ThomasKa 的回答很好。裁剪一种资源将为您节省大量时间,如果做得好,看起来也不错。但是,如果您愿意,可以使用 100 个单独的可绘制对象。

您要做的是适当地命名您的可绘制对象(带有数字后缀),然后按名称获取它们。您可以使用Resources.getIdentifier()它,例如:

Resources res = getResources();
int resId = res.getIdentifier("health" + Health, "drawable", getPackageName());
HealthDisplay.setBackgroundResource(resId);

该示例假设您的可绘制对象被命名为 health100、health99 等,如您的示例所示。

于 2013-02-26T21:01:49.207 回答