当前位置: 首页 > 面试题库 >

使用自定义原始类的android AnalogClock设置时间

山越
2023-03-14
问题内容

我想使用Internet上可用的Android Open Source Project的AnalogClock的源代码制作自定义的AnalogClock类。

我想让时钟设置我想要的时间,而不是当前时间。我没有找到明确的示例,因此这篇文章可能会有用。将源代码复制到新文件后,出现一些错误。以下是AnalogClock的原始源代码:

/*
 * Copyright (C) 2006 The Android Open Source Project
 *
 * 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 android.widget;

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.BroadcastReceiver;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.text.format.Time;
import android.util.AttributeSet;
import android.view.View;
import android.widget.RemoteViews.RemoteView;

import java.util.TimeZone;

/**
 * This widget display an analogic clock with two hands for hours and
 * minutes.
 */
@RemoteView
public class AnalogClock extends View {
    private Time mCalendar;

    private Drawable mHourHand;
    private Drawable mMinuteHand;
    private Drawable mDial;

    private int mDialWidth;
    private int mDialHeight;

    private boolean mAttached;

    private final Handler mHandler = new Handler();
    private float mMinutes;
    private float mHour;
    private boolean mChanged;

    public AnalogClock(Context context) {
        this(context, null);
    }

    public AnalogClock(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

!!错误mContext- >将mContext更改为上下文(我可以这样做)吗?

    public AnalogClock(Context context, AttributeSet attrs,
                       int defStyle) {
        super(context, attrs, defStyle);
        Resources r = mContext.getResources();

!!错误com.android.internal.R无法解决。 我找到了解决此问题的方法

mDial = r.getDrawable(Resources.getSystem().getIdentifier("clock_dial","drawable", "android"));

对于其他行也一样,只是更改名称以及可绘制或可样式化。

vvvv ---- 但是下面的代码仍然有问题。

        TypedArray a =
                context.obtainStyledAttributes(
                        attrs, com.android.internal.R.styleable.AnalogClock, defStyle, 0);

^^^^ ---- 我不知道如何更改它并使之工作

        mDial = a.getDrawable(com.android.internal.R.styleable.AnalogClock_dial);
        if (mDial == null) {
            mDial = r.getDrawable(com.android.internal.R.drawable.clock_dial);
        }

        mHourHand = a.getDrawable(com.android.internal.R.styleable.AnalogClock_hand_hour);
        if (mHourHand == null) {
            mHourHand = r.getDrawable(com.android.internal.R.drawable.clock_hand_hour);
        }

        mMinuteHand = a.getDrawable(com.android.internal.R.styleable.AnalogClock_hand_minute);
        if (mMinuteHand == null) {
            mMinuteHand = r.getDrawable(com.android.internal.R.drawable.clock_hand_minute);
        }

        mCalendar = new Time();

        mDialWidth = mDial.getIntrinsicWidth();
        mDialHeight = mDial.getIntrinsicHeight();
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();

        if (!mAttached) {
            mAttached = true;
            IntentFilter filter = new IntentFilter();

            filter.addAction(Intent.ACTION_TIME_TICK);
            filter.addAction(Intent.ACTION_TIME_CHANGED);
            filter.addAction(Intent.ACTION_TIMEZONE_CHANGED);

            getContext().registerReceiver(mIntentReceiver, filter, null, mHandler);
        }

        // NOTE: It's safe to do these after registering the receiver since the receiver always runs
        // in the main thread, therefore the receiver can't run before this method returns.

        // The time zone may have changed while the receiver wasn't registered, so update the Time
        mCalendar = new Time();

        // Make sure we update to the current time
        onTimeChanged();
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if (mAttached) {
            getContext().unregisterReceiver(mIntentReceiver);
            mAttached = false;
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthSize =  MeasureSpec.getSize(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightSize =  MeasureSpec.getSize(heightMeasureSpec);

        float hScale = 1.0f;
        float vScale = 1.0f;

        if (widthMode != MeasureSpec.UNSPECIFIED && widthSize < mDialWidth) {
            hScale = (float) widthSize / (float) mDialWidth;
        }

        if (heightMode != MeasureSpec.UNSPECIFIED && heightSize < mDialHeight) {
            vScale = (float )heightSize / (float) mDialHeight;
        }

        float scale = Math.min(hScale, vScale);

        setMeasuredDimension(resolveSize((int) (mDialWidth * scale), widthMeasureSpec),
                resolveSize((int) (mDialHeight * scale), heightMeasureSpec));
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        mChanged = true;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        boolean changed = mChanged;
        if (changed) {
            mChanged = false;
        }

!!!错误-mRight,mLeft,mBotton,mTop来自何处? 在此文件中未声明

        int availableWidth = mRight - mLeft;
        int availableHeight = mBottom - mTop;

        int x = availableWidth / 2;
        int y = availableHeight / 2;

        final Drawable dial = mDial;
        int w = dial.getIntrinsicWidth();
        int h = dial.getIntrinsicHeight();

        boolean scaled = false;

        if (availableWidth < w || availableHeight < h) {
            scaled = true;
            float scale = Math.min((float) availableWidth / (float) w,
                                   (float) availableHeight / (float) h);
            canvas.save();
            canvas.scale(scale, scale, x, y);
        }

        if (changed) {
            dial.setBounds(x - (w / 2), y - (h / 2), x + (w / 2), y + (h / 2));
        }
        dial.draw(canvas);

        canvas.save();
        canvas.rotate(mHour / 12.0f * 360.0f, x, y);
        final Drawable hourHand = mHourHand;
        if (changed) {
            w = hourHand.getIntrinsicWidth();
            h = hourHand.getIntrinsicHeight();
            hourHand.setBounds(x - (w / 2), y - (h / 2), x + (w / 2), y + (h / 2));
        }
        hourHand.draw(canvas);
        canvas.restore();

        canvas.save();
        canvas.rotate(mMinutes / 60.0f * 360.0f, x, y);

        final Drawable minuteHand = mMinuteHand;
        if (changed) {
            w = minuteHand.getIntrinsicWidth();
            h = minuteHand.getIntrinsicHeight();
            minuteHand.setBounds(x - (w / 2), y - (h / 2), x + (w / 2), y + (h / 2));
        }
        minuteHand.draw(canvas);
        canvas.restore();

        if (scaled) {
            canvas.restore();
        }
    }

    private void onTimeChanged() {
        mCalendar.setToNow();

        int hour = mCalendar.hour;
        int minute = mCalendar.minute;
        int second = mCalendar.second;

        mMinutes = minute + second / 60.0f;
        mHour = hour + mMinutes / 60.0f;
        mChanged = true;
    }

    private final BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(Intent.ACTION_TIMEZONE_CHANGED)) {
                String tz = intent.getStringExtra("time-zone");
                mCalendar = new Time(TimeZone.getTimeZone(tz).getID());
            }

            onTimeChanged();

            invalidate();
        }
    };
}

谁能告诉我:

  1. 如何使此类像普通的AnalogClock一样工作
  2. 我如何在此类内编写一个方法,该方法将花费我将提供的时间?

问题答案:

使用setTime()方法工作自定义MyAnalogClock。

花了一些时间后,我终于设法解决了这个问题。我希望这对某人有用。您只需调用setTime(hours,minutes,seconds)方法即可设置时间。

import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.text.format.Time;
import android.util.AttributeSet;
import android.view.View;
import android.widget.RemoteViews.RemoteView;

/**
 * This widget display an analogic clock with two hands for hours and
 * minutes.
 */
@RemoteView
public class MyAnalogClock extends View {

    private Drawable mHourHand;
    private Drawable mMinuteHand;
    private Drawable mSecondHand;
    private Drawable mDial;

    private int mDialWidth;
    private int mDialHeight;

    private float mSeconds;
    private float mMinutes;
    private float mHour;

    Context mContext;

    public MyAnalogClock(Context context) {
        super(context);
    }

    public MyAnalogClock(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public MyAnalogClock(Context context, AttributeSet attrs,
                       int defStyle) {
        super(context, attrs, defStyle);
        Resources r = context.getResources();
        TypedArray a =
                context.obtainStyledAttributes(
                        attrs, R.styleable.AnalogClock, defStyle, 0);
        mContext=context;
       // mDial = a.getDrawable(com.android.internal.R.styleable.AnalogClock_dial);
       // if (mDial == null) {
            mDial = r.getDrawable(R.drawable.clock_dial);
       // }

      //  mHourHand = a.getDrawable(com.android.internal.R.styleable.AnalogClock_hand_hour);
      //  if (mHourHand == null) {
            mHourHand = r.getDrawable(R.drawable.clock_hour);
      //  }

     //   mMinuteHand = a.getDrawable(com.android.internal.R.styleable.AnalogClock_hand_minute);
     //   if (mMinuteHand == null) {
            mMinuteHand = r.getDrawable(R.drawable.clock_minute);
            mSecondHand = r.getDrawable(R.drawable.clockgoog_minute);
     //   }

        mDialWidth = mDial.getIntrinsicWidth();
        mDialHeight = mDial.getIntrinsicHeight();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthSize =  MeasureSpec.getSize(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightSize =  MeasureSpec.getSize(heightMeasureSpec);

        float hScale = 1.0f;
        float vScale = 1.0f;

        if (widthMode != MeasureSpec.UNSPECIFIED && widthSize < mDialWidth) {
            hScale = (float) widthSize / (float) mDialWidth;
        }

        if (heightMode != MeasureSpec.UNSPECIFIED && heightSize < mDialHeight) {
            vScale = (float )heightSize / (float) mDialHeight;
        }

        float scale = Math.min(hScale, vScale);

        setMeasuredDimension(resolveSize((int) (mDialWidth * scale), widthMeasureSpec),
                resolveSize((int) (mDialHeight * scale), heightMeasureSpec));
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        //Here you can set the size of your clock
        int availableWidth = 70;
        int availableHeight = 70;

        //Actual size
        int x = availableWidth / 2;
        int y = availableHeight / 2;

        final Drawable dial = mDial;
        int w = dial.getIntrinsicWidth();
        int h = dial.getIntrinsicHeight();

        boolean scaled = false;

        if (availableWidth < w || availableHeight < h) {
            scaled = true;
            float scale = Math.min((float) availableWidth / (float) w,
                                   (float) availableHeight / (float) h);
            canvas.save();
            canvas.scale(scale, scale, x, y);
        }

        dial.setBounds(x - (w / 2), y - (h / 2), x + (w / 2), y + (h / 2));
        dial.draw(canvas);

        canvas.save();
        canvas.rotate(mHour / 12.0f * 360.0f, x, y);
        w = mHourHand.getIntrinsicWidth();
        h = mHourHand.getIntrinsicHeight();
        mHourHand.setBounds(x - (w / 2), y - (h / 2), x + (w / 2), y + (h / 2));
        mHourHand.draw(canvas);
        canvas.restore();

        canvas.save();
        canvas.rotate(mMinutes / 60.0f * 360.0f, x, y);
        w = mMinuteHand.getIntrinsicWidth();
        h = mMinuteHand.getIntrinsicHeight();
        mMinuteHand.setBounds(x - (w / 2), y - (h / 2), x + (w / 2), y + (h / 2));
        mMinuteHand.draw(canvas);
        canvas.restore();

        canvas.save();
        canvas.rotate(mSeconds, x, y);
        w = mSecondHand.getIntrinsicWidth();
        h = mSecondHand.getIntrinsicHeight();
        mSecondHand.setBounds(x - (w / 2), y - (h / 2), x + (w / 2), y + (h / 2));
        mSecondHand.draw(canvas);
        canvas.restore();
        if (scaled) {
            canvas.restore();
        }
    }

    public void setTime(int hours, int minutes, int seconds)
    {
        mSeconds = 6.0f*seconds;
        mMinutes = minutes + seconds / 60.0f;
        mHour = hours + mMinutes / 60.0f;
    }
}

您还应该在可绘制文件夹中放置4个可绘制文件,并使用以下代码在values文件夹中创建(或更新)attrs文件:

<?xml version="1.0" encoding="UTF-8"?>
<resources>
    <declare-styleable name="AnalogClock">
        <attr name="dial" format="reference"/>
        <attr name="hand_hour" format="reference"/>
        <attr name="hand_minute" format="reference"/>
    </declare-styleable>
    </resources>


 类似资料:
  • 是否可以为基元类型定义招摇定义/模型?例如,考虑以下几点 但是,上面的示例返回了许多错误(例如,swagger需要一个字段)并且没有示例使用任何不是。 目的是将其用作另一个模型的子组件和参数——以某种方式重用已经定义的组件。 把这想象成一个昂首阔步的typedef 编辑:根据规范,定义对象与模式对象相同http://swagger.io/specification/#schemaObject,表示

  • 介绍: 现在基于css font-face的字体图标越来越流行。 这种图标具有矢量图的特点,可以不失真的自由缩放,还可以通过css来设置图标的颜色,还有就是网络上资源特别丰富。X5系统自带了数百个字体图标, 用户还可以通过配置使用自己下载的字体图标, 下边就介绍一下具体的使用方法。 首先以fortawesome 网站为例(网址:http://fortawesome.github.io/Font-A

  • 介绍: 现在基于css font-face的字体图标越来越流行。 这种图标具有矢量图的特点,可以不失真的自由缩放,还可以通过css来设置图标的颜色,还有就是网络上资源特别丰富。X5系统自带了数百个字体图标, 用户还可以通过配置使用自己下载的字体图标, 下边就介绍一下具体的使用方法。 首先以fortawesome 网站为例(网址:http://fortawesome.github.io/Font-A

  • 问题内容: 需要使用java.net.URL类进行的远程数据请求超时设置。经过一番谷歌搜索后,发现有两个系统属性可用于设置URL类的超时,如下所示。 我无法控制所有系统,也不希望每个人都继续设置系统属性。是否有其他选择可以进行远程请求,这将允许我设置超时。如果没有任何库,则最好使用Java本身。 问题答案: 如果您要打开from ,则可以通过以下方式设置超时时间: 您如何使用或将其传递给什么?

  • 本章节中,简述自定义类的创建和使用方法,供参考。 创建自定义类 用户可以定义自己的类,通过继承 ThingJS 内部类(比如:Thing 类),对 ThingJS 进行扩展和封装。 我们推荐使用 ES6 语法定义一个类。例如,自定义汽车类 Car。 // 继承 Thing 类 class Car extends THING.Thing { constructor(app) { super(

  • 支持和小程序的原生自定义组件混用,使用方式和原生的使用方式没有区别。在引用时在页面 js 入口配置 config.usingComponents。 export default { config: { usingComponents: { comp: 'path/to/components/comp/index' } } } 另外还需要在 webpack 中配