如何从Android中的public void函数访问自定义视图?

时间:2015-02-27 09:51:08

标签: android location locationlistener

我想从公共类中的public void onLocationChanged访问自定义视图MyCurrentLocationListener实现LocationListener。 MyActivity:

public class MyActivity extends ActionBarActivity {
public final static String EXTRA_MESSAGE = "net.motameni.alisapp.MESSAGE";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    MyCurrentLocationListener locationListener = new MyCurrentLocationListener();
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}

和MyCurrentLocationListener是这样的:

public class MyCurrentLocationListener implements LocationListener {

public void onLocationChanged(Location location) {
    TextView textView = (TextView) findViewById(R.id.location_message);
    textView.setTextSize(40);
    textView.setText("hello");
    setContentView(textView);
}

有什么问题???

1 个答案:

答案 0 :(得分:0)

您无法从非UI功能进行UI更改。

执行此操作要么必须将视图对象传递给侦听器方法,要么必须在活动类中创建一个方法,该方法从侦听器接收值并更新视图的值。

更新你的oncreate中的代码:

TextView tv = (TextView)findViewById(R.id.tv1);
MyCurrentLocationListener locationListener = new MyCurrentLocationListener(tv);

并在你的监听器类中创建一个构造函数 -

  TextView textView;
  public MyCurrentLocationListener (TextView  tv){
        textView = tv;
  }

并表格位置变更 -

public void onLocationChanged(Location location) {

 textView.setTextSize(40);
 textView.setText("hello");
}

这是最好的方式。