【问题标题】:Counter for Images Displayed显示图像计数器
【发布时间】:2019-06-29 13:16:02
【问题描述】:

我有一个工作应用程序,从服务器下载图像,存储在本地,并每隔几秒以幻灯片形式显示在图像视图中。我想计算每个图像显示了多少次。我不确定如何解决这个问题。我应该制作 6 个计数器(每个图像一个)还是应该创建一个数组来存储图像名称和计数?但是如何更新呢?

任何帮助或代码 sn-ps 将不胜感激。

 protected void onPostExecute(String s) {
        super.onPostExecute(s);
        imageView = findViewById(R.id.imgholder);
        Timer mTimer = new Timer();
        mTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                // As timer is not a Main/UI thread need to do all UI task on runOnUiThread
                DashboardActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // increase your position so new image will show
                        position++;
                        // check whether position increased to length then set it to 0
                        // so it will show images in circuler
                        if (position >= 6)
                            position = 0;
                        File file = new File(Environment.getExternalStorageDirectory(), user.fullName + "-" + position + ".jpg");
                        imgUri = Uri.fromFile(file);
                        Log.v("test", "Now Showing Image: " + imgUri.toString());

                        // Set Image
                        imageView.setImageURI(imgUri);
                        counter++;
                        Log.v("test","Image: "+ position +" has appeared: " +counter);
                    }
                });
            }
        }, 0, DELAY_TIMER);

【问题讨论】:

  • 来自服务器的图像数量是否固定?号码会变吗?还是您正在从服务器刷新图像?
  • 图像数量是固定的。将下载 6 张图像。图像可能会从服务器更改,但它们将始终为 6。
  • 每张图片都有唯一的id吗?
  • 你应该有类似的东西来区分每个图像
  • @Antonio 是的,每个图像都有唯一的 ID。图像被命名为 0-5。

标签: java android arrays imageview


【解决方案1】:

创建一个长度为 6 的整数数组int[] counters = new int[]{0,0,0,0,0},然后在代码中的if(position >= 6) position = 0; 之后,将计数器递增为counters[position]++;。因此,您始终可以从数组counters 中跟踪特定位置的图像计数

【讨论】:

  • 谢谢。我会对其进行测试并回复您。
【解决方案2】:

创建一个HashMap来存储计数

private HashMap<String, Integer> countMap = new HashMap<>();

现在每当您在方法下方设置图像调用时:

private void updateDisplayCount(File file) {
 if(countMap.containsKey(file.getName())) {
   countMap.put(file.getName(), countMap.get(file.getName()) + 1);
 } else {
   countMap.put(file.getName(), 1);
 }
}

以下代码将返回显示计数

int count = countMap.get(file.getName())

【讨论】:

  • 谢谢。我会测试一下并回复你
  • 这个答案也是正确的。这是一种更整洁的方法。但对于我的用法,另一个答案更简单。如果您有可变数量的图像,请使用 Hashmap。如果您的图像是固定的,您可以选择下面提供的更简单的解决方案
  • @SaeedJoul 如果您觉得有用,请点赞。谢谢。
猜你喜欢
  • 2012-07-18
  • 1970-01-01
  • 2012-11-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-17
相关资源
最近更新 更多