在我的oncreate方法中,我有这个:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game_activity);
mContext = this;
}
mContext
是整个班级的静态Context
。
然而,即使我这样做,我也不能这样做:
mContext.findViewById(R.id.score_text);
它说它无法解决方法" findViewbyId"
我做错了什么?
答案 0 :(得分:0)
你在活动中,我认为你可以直接使用findViewById。就像那样:
findViewById
代替mContext.findViewById
答案 1 :(得分:0)
mContext是整个类的静态上下文
请删除此内容。
我做错了什么?
findViewById()
是Activity
和Fragment
上的一种方法。它不是Context
上的方法。
由于您致电setContentView()
,因此您的onCreate()
方法属于某项活动,因此您只需致电findViewById()
:
/***
Copyright (c) 2012 CommonsWare, LLC
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.
From _The Busy Coder's Guide to Android Development_
https://commonsware.com/Android
*/
package com.commonsware.android.extra;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class OtherActivity extends Activity {
public static final String EXTRA_MESSAGE="msg";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.other);
TextView tv=(TextView)findViewById(R.id.msg);
tv.setText(getIntent().getStringExtra(EXTRA_MESSAGE));
}
}
答案 2 :(得分:0)
替换:
mContext.findViewById(R.id.score_text);
与
findViewById(R.id.score_text);
活动已有findViewById方法