从外部类访问TextView

时间:2012-03-09 09:52:57

标签: android

我是Android和Java的新手,希望你能帮助我。

我有一个嵌套类:

public class MyLocationListener implements LocationListener

  {


    public void onLocationChanged(Location loc)

    {
        loc.getLatitude();
        loc.getLongitude();

        String loTude = "Longitude:" + loc.getLongitude();
        String laTude = "Latitude: " + loc.getLatitude();

        ((TextView) findViewById(R.id.tvLong)).setText(loTude);
        ((TextView) findViewById(R.id.tvLat)).setText(laTude);



    }

我怎样才能从外面的班级中获取两个Strings loTude和laTude? 我是否需要通过对象从方法中返回它们,还是有其他方式?

3 个答案:

答案 0 :(得分:1)

如果您有嵌套类,那么将textview的Global对象设为像....

    Class MyActivity extends Activity{
      public TextView tvLat,tvLng;
       @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);

           tvLat=(TextView) findViewById(R.id.tvLong);
           tvLng=(TextView) findViewById(R.id.tvLat);

     }
    public class MyLocationListener implements LocationListener
        {
            public void onLocationChanged(Location loc)
              {
            loc.getLatitude();
            loc.getLongitude();

            String loTude = "Longitude:" + loc.getLongitude();
            String laTude = "Latitude: " + loc.getLatitude();

            tvLat.setText(loTude);
            tvLng.setText(laTude);

        }
    }
 }

答案 1 :(得分:0)

您可以将活动的引用传递给自定义类。见下文:

public class MyLocationListener implements LocationListener
{

  private Activity myActivity;

  public MyLocationListener(Activity act){
      myActivity = act;
  }

  public void onLocationChanged(Location loc){
      loc.getLatitude();
      loc.getLongitude();

      String loTude = "Longitude:" + loc.getLongitude();
      String laTude = "Latitude: " + loc.getLatitude();

      ((TextView) myActivity.findViewById(R.id.tvLong)).setText(loTude);
      ((TextView) myActivity.findViewById(R.id.tvLat)).setText(laTude);

  }

}
如果您已单独定义了课程,建议使用此解决方案。否则,在onCreate方法中查找您的视图,并在内部类中使用它们

答案 2 :(得分:0)

创建一个这样的类

public class Global extends Application {
   public static String loTude =""; 
   public static String laTude ="";
}

用于字符串值

Global.loTude = "Longitude:" + loc.getLongitude();
Global.laTude = "Latitude: " + loc.getLatitude();