[英]How to properly set information to ArrayList TextView that is being inflated from a single List Item?
對於可能令人困惑的標題,我事先表示歉意,我不確定該如何表達問題,但我會盡力清楚地說明我的問題是什么...
當我嘗試設置TextViews的文本以顯示各個距離時,就會出現我的問題。 我在list_item.xml中使用單個TextView,然后我的Custom ArrayAdapter對其進行膨脹並填充ListView(word_list.xml)。
我嘗試了許多方法,但僅使用一種特定的方法“成功”了-它僅最終用數據填充了第一個列表項,而沒有填充其余的數據。
我的主要問題是mFormattedDistanceString
(位於我在此處復制的ListView活動的最底部)。 它是我所有計算出的位置距離信息所駐留的變量。 我似乎無法將其設置為ArrayList中的TextViews。 我覺得答案可能很簡單,但是我似乎無法直截了當-我已經嘗試了許多我研究過的選項,但都沒有用。
ArrayAdapter的自定義數據類型。
public class Word {
private String mName;
private int mImageResourceId = NO_IMAGE_PROVIDED;
private double mDistanceLat;
private double mDistanceLong;
private String mLocationData;
private static final int NO_IMAGE_PROVIDED = -1;
public Word(String name) {
mName = name;
}
public Word(String name, int imageResourceId) {
mName = name;
mImageResourceId = imageResourceId;
}
public Word(String name, int imageResourceId, double distanceLat, double distanceLong,
String locationData){
mName = name;
mImageResourceId = imageResourceId;
mDistanceLat = distanceLat;
mDistanceLong = distanceLong;
mLocationData = locationData;
}
public Word(int imageResourceId) {
mImageResourceId = imageResourceId;
}
public String getName() {
return mName;
}
public int getImageResourceId() {
return mImageResourceId;
}
public double getDistanceLat() {
return mDistanceLat;
}
public double getDistanceLong() {
return mDistanceLong;
}
public String getLocationData() {
return mLocationData;
}
public boolean hasImage() {
return mImageResourceId != NO_IMAGE_PROVIDED;
}
}
自定義ArrayAdapter。
我已經研究了幾個小時,甚至嘗試了getView方法中的幾種不同方法,但是我無法獲取所有列表項來顯示數據,僅顯示列表中的第一個元素。
public class LocationsAdapter extends ArrayAdapter<Word> {
private LayoutInflater mInflater;
private Context mContext;
private Location mLocation;
private String mFormattedDistanceString;
static class ViewHolder {
TextView text;
ImageView image;
TextView distanceText;
}
public LocationsAdapter(Activity context, List<Word> locations, String formattedDistanceString) {
super(context, 0, locations);
mContext = context;
mInflater = LayoutInflater.from(context);
mFormattedDistanceString = formattedDistanceString;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
Word currentWord = getItem(position);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item, parent, false);
viewHolder = new ViewHolder();
viewHolder.text = (TextView) convertView.findViewById(R.id.name_text_view);
viewHolder.image = (ImageView) convertView.findViewById(R.id.icon_image_view);
viewHolder.distanceText = (TextView) convertView.findViewById(R.id.distance_text_view);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.text.setText(currentWord.getName());
viewHolder.distanceText.setText(currentWord.getLocationData());
if (currentWord.hasImage())
{
viewHolder.image.setVisibility(View.VISIBLE);
} else {
viewHolder.image.setVisibility(View.GONE);
}
return convertView;
}
}
我的ListView活動之一。
public class Locations extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, LocationListener {
private static final int PERMISSION_REQUEST_ACCESS_FINE_LOCATION = 100;
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
private static final String LOG_TAG = Locations.class.getName();
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
private String mFormattedDistanceString;
public List<Word> locations = new ArrayList<>();
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[],
int[] grantResults) {
switch (requestCode) {
case PERMISSION_REQUEST_ACCESS_FINE_LOCATION: {
mGoogleApiClient.connect();
}
}
}
private String simplifiedMilesDecimal(double miles) {
DecimalFormat simplifiedDistance = new DecimalFormat("0.0 Miles Away");
return simplifiedDistance.format(miles);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.word_list);
if (ContextCompat.checkSelfPermission(this,
ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
ACCESS_FINE_LOCATION)) {
} else {
ActivityCompat.requestPermissions(this,
new String[]{ACCESS_FINE_LOCATION},
PERMISSION_REQUEST_ACCESS_FINE_LOCATION);
}
}
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(10 * 1000) // 10 seconds, in milliseconds
.setFastestInterval(1 * 1000); // 1 second, in milliseconds
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
locations.add(new Word("Bristol", R.drawable.bristol,
41.670374, -71.276565, mFormattedDistanceString));
locations.add(new Word("Warren", R.drawable.warren,
41.729085, -71.282283, mFormattedDistanceString));
locations.add(new Word("Newport", R.drawable.newport_breakers,
41.486677, -71.315144, mFormattedDistanceString));
locations.add(new Word("Jamestown", R.drawable.jamestown,
41.496313, -71.368435, mFormattedDistanceString));
locations.add(new Word("Beavertail", R.drawable.beavertail,
41.458054, -71.395744, mFormattedDistanceString));
locations.add(new Word("Providence", R.drawable.providence,
41.830279, -71.414955, mFormattedDistanceString));
locations.add(new Word("Roger Williams Park", R.drawable.roger_williams_park,
41.788673, -71.414179, mFormattedDistanceString));
locations.add(new Word("Colt State Park", R.drawable.colt_state_park,
41.677248, -71.298871, mFormattedDistanceString));
ListView listView = (ListView) findViewById(R.id.list);
ViewCompat.setNestedScrollingEnabled(listView, true);
listView.setAdapter(new LocationsAdapter(this, locations, mFormattedDistanceString));
// Set a click listener to open the default Maps app when the list item is clicked on
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
if (position == 0) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("geo:41.670374, -71.276565?z=15"));
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
} else if (position == 1) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("geo:41.729085, -71.282283?z=15"));
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
} else if (position == 2) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("geo:41.486677, -71.315144?z=13"));
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
} else if (position == 3) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("geo:41.496313, -71.368435?z=14"));
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
} else if (position == 4) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("geo:41.458054, -71.395744?z=14"));
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
} else if (position == 5) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("geo:41.830279, -71.414955?z=14"));
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
} else if (position == 6) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("geo:41.788673, -71.414179?z=16"));
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
} else if (position == 7) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("geo:41.677248, -71.298871?z=14"));
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
}
}
});
}
@Override
protected void onStart() {
if (ContextCompat.checkSelfPermission(this,
ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
mGoogleApiClient.connect();
}
super.onStart();
}
@Override
protected void onResume() {
if (ContextCompat.checkSelfPermission(this,
ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
mGoogleApiClient.connect();
}
super.onResume();
}
@Override
protected void onPause() {
super.onPause();
if (mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient,
this);
mGoogleApiClient.disconnect();
}
}
protected void onStop() {
// If the user has stopped the app, disconnect from the GoogleApiClient.
mGoogleApiClient.disconnect();
super.onStop();
}
@Override
public void onConnected(@Nullable Bundle bundle) {
Log.i(LOG_TAG, "Location services connected.");
Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (location == null) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,
mLocationRequest, this);
} else {
handleNewLocation(location);
}
}
@Override
public void onConnectionSuspended(int i) {
Log.i(LOG_TAG, "Location services suspended. Please reconnect.");
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
if (connectionResult.hasResolution()) {
try {
// Start an Activity that tries to resolve the error
connectionResult.startResolutionForResult(this,
CONNECTION_FAILURE_RESOLUTION_REQUEST);
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
}
} else {
Log.i(LOG_TAG, "Location services connection failed with code " +
connectionResult.getErrorCode());
}
}
@Override
public void onLocationChanged(Location location) {
handleNewLocation(location);
}
private void handleNewLocation(Location location) {
Log.d(LOG_TAG, location.toString());
LatLng currentUserCoord = new LatLng(location.getLatitude(), location.getLongitude());
Word locationsListItem = locations.get(0);
LatLng destinationCoord = new LatLng(locationsListItem.getDistanceLat(),
locationsListItem.getDistanceLong());
double distanceInMiles =
LatLngTool.distance(currentUserCoord, destinationCoord, LengthUnit.MILE);
String formattedDistance = simplifiedMilesDecimal(distanceInMiles);
mFormattedDistanceString = toString().valueOf(formattedDistance);
Log.i(LOG_TAG, mFormattedDistanceString);
}
}
我嘗試在Locations Activity中使用for循環來遍歷ArrayList中的元素,但是我不確定是否將其設置為錯誤,或者它是否不是解決問題的正確方法。
最好的方法是以某種方式獲取保存在mFormattedDistanceString
的位置數據並將其傳遞給LocationsAdapter,以便getView
方法可以執行其操作並使用距離信息填充ListView,就像對ImageViews所做的一樣,等等?
讓我知道我是否錯了,以及您認為我應該怎么做!
更新
這是我的代碼塊,其中包含@cark建議的更改,因此我們可以找到解決方案...我覺得這很簡單,但是我無法弄清楚-有太多變量,引用和方法可以跟蹤的... :(
詞類。
public class Word {
private static final String LOG_TAG = Word.class.getName();
private String mName;
private int mImageResourceId = NO_IMAGE_PROVIDED;
private double mDistanceLat;
private double mDistanceLong;
private Location currentLocation;
private String mFormattedDistanceString;
private String simplifiedMilesDecimal(double miles) {
DecimalFormat simplifiedDistance = new DecimalFormat("0.0 Miles Away");
return simplifiedDistance.format(miles);
}
public void updateDistance(Location location){
if(location.equals(currentLocation)) return;
LatLng currentUserCoord = new LatLng(location.getLatitude(), location.getLongitude());
Log.i(LOG_TAG, toString().valueOf(currentUserCoord));
LatLng destinationCoord = new LatLng(this.getDistanceLat(),
this.getDistanceLong());
double distanceInMiles =
LatLngTool.distance(currentUserCoord, destinationCoord, LengthUnit.MILE);
String formattedDistance = simplifiedMilesDecimal(distanceInMiles);
mFormattedDistanceString = toString().valueOf(formattedDistance);
currentLocation = location;
}
private static final int NO_IMAGE_PROVIDED = -1;
public Word(String name) {
mName = name;
}
public Word(String name, int imageResourceId) {
mName = name;
mImageResourceId = imageResourceId;
}
public Word(String name, int imageResourceId, double distanceLat, double distanceLong,
String formattedDistanceString){
mName = name;
mImageResourceId = imageResourceId;
mDistanceLat = distanceLat;
mDistanceLong = distanceLong;
mFormattedDistanceString = formattedDistanceString;
}
public Word(String name, int imageResourceId, double distanceLat, double distanceLong){
mName = name;
mImageResourceId = imageResourceId;
mDistanceLat = distanceLat;
mDistanceLong = distanceLong;
}
public Word(int imageResourceId) {
mImageResourceId = imageResourceId;
}
public String getName() {
return mName;
}
public int getImageResourceId() {
return mImageResourceId;
}
public double getDistanceLat() {
return mDistanceLat;
}
public double getDistanceLong() {
return mDistanceLong;
}
public String getFormattedDistance() {
return mFormattedDistanceString;
}
public boolean hasImage() {
return mImageResourceId != NO_IMAGE_PROVIDED;
}
}
LocationsAdapter類。
public class LocationsAdapter extends ArrayAdapter<Word> {
private LayoutInflater mInflater;
private Context mContext;
private Location mLocation;
static class ViewHolder {
TextView text;
ImageView image;
TextView distanceText;
}
public LocationsAdapter(Activity context, List<Word> locations, Location location) {
super(context, 0, locations);
mLocation = location;
mContext = context;
mInflater = LayoutInflater.from(context);
}
public void setCurrentLocation(Location lastLocation)
{
mLocation = lastLocation;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
Word currentWord = getItem(position);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item, parent, false);
viewHolder = new ViewHolder();
viewHolder.text = (TextView) convertView.findViewById(R.id.name_text_view);
viewHolder.image = (ImageView) convertView.findViewById(R.id.icon_image_view);
viewHolder.distanceText = (TextView) convertView.findViewById(R.id.distance_text_view);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.text.setText(currentWord.getName());
currentWord.updateDistance(mLocation);
viewHolder.distanceText.setText(currentWord.getFormattedDistance());
if (currentWord.hasImage())
{
viewHolder.image.setImageResource(currentWord.getImageResourceId());
viewHolder.image.setVisibility(View.VISIBLE);
} else {
// Otherwise hide the ImageView (set visibility to GONE)
viewHolder.image.setVisibility(View.GONE);
}
return convertView;
}
}
位置活動。
public class Locations extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, LocationListener {
private static final int PERMISSION_REQUEST_ACCESS_FINE_LOCATION = 100;
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
private static final String LOG_TAG = Locations.class.getName();
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
private String mFormattedDistanceString;
Location mLocation = new Location(LocationManager.NETWORK_PROVIDER);
private ListView mListView;
public List<Word> locations = new ArrayList<>();
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[],
int[] grantResults) {
switch (requestCode) {
case PERMISSION_REQUEST_ACCESS_FINE_LOCATION: {
mGoogleApiClient.connect();
}
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.word_list);
mListView = (ListView) findViewById(R.id.list);
if (ContextCompat.checkSelfPermission(this,
ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
ACCESS_FINE_LOCATION)) {
} else {
ActivityCompat.requestPermissions(this,
new String[]{ACCESS_FINE_LOCATION},
PERMISSION_REQUEST_ACCESS_FINE_LOCATION);
}
}
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(10 * 1000) // 10 seconds, in milliseconds
.setFastestInterval(1 * 1000); // 1 second, in milliseconds
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mFormattedDistanceString = new String();
locations.add(new Word("Bristol", R.drawable.bristol,
41.670374, -71.276565, mFormattedDistanceString));
locations.add(new Word("Warren", R.drawable.warren,
41.729085, -71.282283, mFormattedDistanceString));
locations.add(new Word("Newport", R.drawable.newport_breakers,
41.486677, -71.315144, mFormattedDistanceString));
locations.add(new Word("Jamestown", R.drawable.jamestown,
41.496313, -71.368435, mFormattedDistanceString));
locations.add(new Word("Beavertail", R.drawable.beavertail,
41.458054, -71.395744, mFormattedDistanceString));
locations.add(new Word("Providence", R.drawable.providence,
41.830279, -71.414955, mFormattedDistanceString));
locations.add(new Word("Roger Williams Park", R.drawable.roger_williams_park,
41.788673, -71.414179, mFormattedDistanceString));
locations.add(new Word("Colt State Park", R.drawable.colt_state_park,
41.677248, -71.298871, mFormattedDistanceString));
ViewCompat.setNestedScrollingEnabled(mListView, true);
mListView.setAdapter(new LocationsAdapter(this, locations, mLocation));
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
if (position == 0) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("geo:41.670374, -71.276565?z=15"));
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
} else if (position == 1) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("geo:41.729085, -71.282283?z=15"));
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
} else if (position == 2) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("geo:41.486677, -71.315144?z=13"));
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
} else if (position == 3) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("geo:41.496313, -71.368435?z=14"));
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
} else if (position == 4) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("geo:41.458054, -71.395744?z=14"));
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
} else if (position == 5) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("geo:41.830279, -71.414955?z=14"));
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
} else if (position == 6) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("geo:41.788673, -71.414179?z=16"));
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
} else if (position == 7) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("geo:41.677248, -71.298871?z=14"));
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
}
}
});
}
@Override
protected void onStart() {
// If the app already has the permission to access the user's location at high accuracy
// (fine location), then connect to the GoogleApiClient.
if (ContextCompat.checkSelfPermission(this,
ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
mGoogleApiClient.connect();
}
super.onStart();
}
@Override
protected void onResume() {
if (ContextCompat.checkSelfPermission(this,
ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
mGoogleApiClient.connect();
}
super.onResume();
}
@Override
protected void onPause() {
super.onPause();
if (mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient,
this);
mGoogleApiClient.disconnect();
}
}
protected void onStop() {
// If the user has stopped the app, disconnect from the GoogleApiClient.
mGoogleApiClient.disconnect();
super.onStop();
}
@Override
public void onConnected(@Nullable Bundle bundle) {
Log.i(LOG_TAG, "Location services connected.");
mLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLocation == null) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,
mLocationRequest, this);
} else {
handleNewLocation(mLocation);
}
}
@Override
public void onConnectionSuspended(int i) {
Log.i(LOG_TAG, "Location services suspended. Please reconnect.");
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
if (connectionResult.hasResolution()) {
try {
connectionResult.startResolutionForResult(this,
CONNECTION_FAILURE_RESOLUTION_REQUEST);
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
}
} else {
Log.i(LOG_TAG, "Location services connection failed with code " +
connectionResult.getErrorCode());
}
}
@Override
public void onLocationChanged(Location location) {
LocationsAdapter adapter = (LocationsAdapter) mListView.getAdapter();
adapter.setCurrentLocation(location);
adapter.notifyDataSetChanged();
}
private void handleNewLocation(Location location) {
Log.d(LOG_TAG, location.toString());
}
}
嘗試這個:
調用onLocationChanged
時,將位置傳遞給LocationsAdapter(創建方法setCurrentLocation
)。
調用(LocationsAdapter)(listView.getAdapter()).notifyDataSetChanged();
(listView必須成為一個類字段)
在適配器的getView
,計算距離並將文本設置為textView。
為了優化距離計算,您可以將值存儲在模型中,但請記住也要存儲Location對象。 這樣,您可以在以后的調用中檢查Location對象是否已更改。 如果“位置”對象發生更改,則需要重新計算距離,否則可以顯示上一次計算的距離。
更新
刪除private String mFormattedDistanceString;
來自LocationsAdapter
。 您不需要它,也可以將其從構造函數中刪除。
在LocationsAdapter
您具有mLocation
,但從未分配它。 將此方法添加到LocationsAdapter
以便在您的活動發生更改時分配mLocation。
public void setCurrentLocation(Location lastLocation){ mLocation = lastLocation}
使listView
成為Locations
活動的一個字段,並以這種方式更改onLocationChanged
:
public void onLocationChanged(Location location) {
LocationsAdapter adapter = (LocationsAdapter)listView.getAdapter();
adapter.setCurrentLocation(location);
adapter.notifyDataSetChanged();
}
在您的Word
類中創建此方法:
Location currentLocation;
public void updateDistance(Location location){
if(location.equals(currentLocation)) return;
//calculate the distance and create the distance string, and set it
//as a class field (you can call it mFormattedDistanceString)
currentLocation = location;
}
在適配器的getView
中,調用updateDistance
,然后使用Word
mFormattedDistanceString
設置TextView文本。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.