相对而言,我还是比较陌生的,因为我在 Activity 类MainActivity中使用的非 Activity 类MyLocation中查找 View 时遇到了问题。我正在使用MyLocation获取经度和纬度。
我想在使用GPS或网络时突出显示文本 View 。为此,我需要在非 Activity 类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);

}

这是我在MyLocation中尝试查找文本 View 的内容:
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) {
    }
};

但是找不到 View 。我已经得到了NPE @ .getSystemService(Context.LAYOUT_INFLATER_SERVICE);。我究竟做错了什么?

最佳答案



因为contextnull类中的MyLocation。使用MyLocation类构造函数在MainActivity中传递MyLocation上下文,以如下方式访问系统服务:

Activity activity;
public MyLocation(Context context,Activity activity){
this.context=context;
this.activity=activity;
}

并在MainActivity中通过将MainActivity上下文传递为来创建MyLocation类对象:
MyLocation myLocation = new MyLocation(MainActivity.this,this);

现在使用context来访问MyLocation类中的系统服务

编辑:而不是在onLocationChanged中再次夸大主布局,请使用Activity上下文从Activity Layout访问 View ,如下所示:
 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);

       ....
    }

10-07 22:28