我正在制作一个“刮刮票”类型的视图,但它正在刮掉黑白叠加层以显示颜色,我试图允许弃用getDrawable,但我对上下文感到困惑。我的代码是:
public class ScratchView extends View{....
public void setOverlay(int id)
{
Bitmap orig = Bitmap.createBitmap(gameWidth, gameHeight, Bitmap.Config.ARGB_4444);
Drawable tDrawable;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
tDrawable = mActivity.getResources().getDrawable(id, context.getTheme());
} else {
tDrawable = mActivity.getResources().getDrawable(id);
}
获取lollipop及更高版本的上下文的正确命令是什么?
答案 0 :(得分:0)
当您创建一个源自查看的新课程时, 你必须创建匹配super的构造函数。 所以你可以得到上下文。
public class ScratchView extends View {
public ScratchView(Context context) {
super(context);
}
}
答案 1 :(得分:0)
您可以使用ContextCompat来避免评估Android的版本。
视图的上下文通常是您的Activity的上下文,它是相同的活动。
从片段中,您可以使用getContext()获取活动的上下文。
答案 2 :(得分:0)
您可以使用View类中的getContext()。每个扩展View的类如LinearLayout,RelativeLayout等都有这个。
https://developer.android.com/reference/android/view/View.html#getContext()
或者您可以在默认构造函数
上初始化上下文public AwesomeView(Context context) {
mContext = context;
}
答案 3 :(得分:-1)
1.创建MyApplication,在AndroidManifest.xml中解析MyApplication
公共类MyApplication扩展了Application {
MyApplication myApplication = MyApplication.getInstances();
myApplication.getApplicationContext();//this is the context you want
}
2.在ScratchView中使用这些代码
import Inferno from "inferno";
import { connect } from "inferno-redux";
import * as actions from "./../actions/actions";
import Component from "inferno-component";
import moment from "moment";
export class Todo extends Component {
render() {
moment.locale("pt-br");
var { id, text, completed, createdAt, completedAt, dispatch } = this.props;
var todoClassName = completed ? "todo todo-completed" : "todo";
var renderDate = () => {
var message = "Criado em ";
var timestamp = createdAt;
if (completed) {
message = "Completa em ";
timestamp = completedAt;
}
return message + moment(timestamp).format("DD/MM/YYYY @ HH:mm:ss");
};
return (
<div
className={todoClassName}
onClick={() => {
dispatch(actions.toggleTodo(id));
}}
>
<div>
<input type="checkbox" checked={completed} />
</div>
<div>
<p>{text}</p>
<p className="todo__subtext">{renderDate()}</p>
</div>
</div>
);
}
}
export default connect()(Todo);