sas*_*cha 8 android layout-inflater
仍然是相对较新的我在我的活动类MainActivity中使用的非活动类MyLocation中找到视图时遇到问题.我正在使用MyLocation来获取经度和纬度.我想在使用GPS或网络时突出显示文本视图.为此,我需要在非活动类MyLocation中查找textviews.
以下是我在MainActivity中调用它的方式:
public class MainActivity extends ActionBarActivity implements LocationListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
MyLocation myLocation = new MyLocation();
myLocation.getLocation(this, locationResult);
}
Run Code Online (Sandbox Code Playgroud)
在这里我在MyLocation中尝试查找textviews:
public class MyLocation {
LocationManager lm;
LocationResult locationResult;
private Context context;
TextView tvnetwork, tvgps;
private int defaultTextColor;
LocationListener locationListenerNetwork = new LocationListener() {
public void onLocationChanged(Location location) {
locationResult.gotLocation(location);
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.main, null);
tvnetwork = (TextView) v.findViewById(R.id.tvnetwork);
tvgps = (TextView) v.findViewById(R.id.tvgps);
defaultTextColor = tvgps.getTextColors().getDefaultColor();
tvnetwork.setTextColor(context.getResources().getColor(
R.color.green));
tvgps.setTextColor(defaultTextColor);
lm.removeUpdates(this);
lm.removeUpdates(locationListenerGps);
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
Run Code Online (Sandbox Code Playgroud)
但没有找到意见.我已经获得了NPE @ .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
.我究竟做错了什么?
ρяσ*_*я K 13
获取NPE @ .getSystemService(Context.LAYOUT_INFLATER_SERVICE);. 我究竟做错了什么?
因为context
是null
在MyLocation
类.使用MyLocation
类构造函数将MainActivity
上下文传递MyLocation
给访问系统服务:
Activity activity;
public MyLocation(Context context,Activity activity){
this.context=context;
this.activity=activity;
}
Run Code Online (Sandbox Code Playgroud)
并通过将MainActivity上下文传递为MainActivity
创建MyLocation
类对象:
MyLocation myLocation = new MyLocation(MainActivity.this,this);
Run Code Online (Sandbox Code Playgroud)
现在用于context
访问MyLocation
类中的系统服务
编辑:而不是在onLocationChanged中再次膨胀主布局使用Activity上下文从Activity Layout访问视图:
public void onLocationChanged(Location location) {
....
tvnetwork = (TextView) activity.findViewById(R.id.tvnetwork);
tvgps = (TextView) activity.findViewById(R.id.tvgps);
defaultTextColor = tvgps.getTextColors().getDefaultColor();
tvnetwork.setTextColor(context.getResources().getColor(
R.color.green));
tvgps.setTextColor(defaultTextColor);
....
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
13520 次 |
最近记录: |