android – findViewById在非Activity类中

前端之家收集整理的这篇文章主要介绍了android – findViewById在非Activity类中前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
仍然是相对较新的我在查找我在活动类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);

}

在这里我在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) {
    }
};

但没有找到意见.我已经获得了NPE @ .getSystemService(Context.LAYOUT_INFLATER_SERVICE);.我究竟做错了什么?

解决方法

get a NPE @ .getSystemService(Context.LAYOUT_INFLATER_SERVICE);. What
am I doing wrong?

因为MyLocation类中的上下文为null.使用MyLocation类构造函数在MyLocation中传递MainActivity上下文以访问系统服务:

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

并在MainActivity中通过将MainActivity上下文传递为:创建MyLocation类对象:

MyLocation myLocation = new MyLocation(MainActivity.this,this);

现在使用上下文访问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);

       ....
    }
原文链接:https://www.f2er.com/android/316818.html

猜你在找的Android相关文章