简体   繁体   English

如何正确地设置信息从单个列表项膨胀到ArrayList TextView?

[英]How to properly set information to ArrayList TextView that is being inflated from a single List Item?

I apologize in advance for the potentially confusing title, I'm not exactly sure how to phrase the question, but I'll try to clearly explain what my issue is... 对于可能令人困惑的标题,我事先表示歉意,我不确定该如何表达问题,但我会尽力清楚地说明我的问题是什么...

My issue arises when I'm trying to set the text of the TextViews to display the individual distances. 当我尝试设置TextViews的文本以显示各个距离时,就会出现我的问题。 I'm using a single TextView in a list_item.xml which my Custom ArrayAdapter then inflates and populates the ListView (word_list.xml) with. 我在list_item.xml中使用单个TextView,然后我的Custom ArrayAdapter对其进行膨胀并填充ListView(word_list.xml)。

I've tried many methods, but I've only "succeeded" with one specific method - it only ended up populating the first list item with the data, but not the rest of them. 我尝试了许多方法,但仅使用一种特定的方法“成功”了-它仅最终用数据填充了第一个列表项,而没有填充其余的数据。

My prime issue is with mFormattedDistanceString (found at the very bottom of the ListView Activity I've copied here). 我的主要问题是mFormattedDistanceString (位于我在此处复制的ListView活动的最底部)。 It is the variable in which all my calculated location distance information resides. 它是我所有计算出的位置距离信息所驻留的变量。 I can't seem to get it to set to the TextViews within the ArrayList. 我似乎无法将其设置为ArrayList中的TextViews。 I feel like the answer might be simple, but I just can't seem to think straight with it - I've tried many different options that I've researched, to no avail. 我觉得答案可能很简单,但是我似乎无法直截了当-我已经尝试了许多我研究过的选项,但都没有用。

Custom Data Type for ArrayAdapter. 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;
}
}

Custom ArrayAdapter. 自定义ArrayAdapter。

I've researched for hours and even tried a few different methods within the getView method, but I couldn't get all my list-items to display the data, only the first element in the list. 我已经研究了几个小时,甚至尝试了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;
}
}

One of my ListView Activites. 我的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);
    }
}

I tried using a for-loop within the Locations Activity to iterate through the elements in the ArrayList, but I'm not sure if I set it up wrong or if it just isn't the right way to go about solving the problem. 我尝试在Locations Activity中使用for循环来遍历ArrayList中的元素,但是我不确定是否将其设置为错误,或者它是否不是解决问题的正确方法。

Is the best way to go about it to somehow get the location data held within mFormattedDistanceString and pass it to the LocationsAdapter so that the getView method can do its thing and populate the ListView with the distance information, just like it already does with the ImageViews, etc? 最好的方法是以某种方式获取保存在mFormattedDistanceString的位置数据并将其传递给LocationsAdapter,以便getView方法可以执行其操作并使用距离信息填充ListView,就像对ImageViews所做的一样,等等?

Let me know if I'm wrong and what you think I should do! 让我知道我是否错了,以及您认为我应该怎么做!

UPDATE 更新

Here are my blocks of code with the changes suggested by @cark so we can find the solution... I feel like it's something quite simple, but I can't figure it out - so many variables, references, and methods to keep track of... :( 这是我的代码块,其中包含@cark建议的更改,因此我们可以找到解决方案...我觉得这很简单,但是我无法弄清楚-有太多变量,引用和方法可以跟踪的... :(

Word class. 词类。

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 class. 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;
    }
}

Locations Activity. 位置活动。

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());

    }
}

try this: 尝试这个:

  • when the onLocationChanged is called, pass the Location to the LocationsAdapter (create the method setCurrentLocation ). 调用onLocationChanged时,将位置传递给LocationsAdapter(创建方法setCurrentLocation )。

  • call (LocationsAdapter)(listView.getAdapter()).notifyDataSetChanged(); 调用(LocationsAdapter)(listView.getAdapter()).notifyDataSetChanged(); (listView has to become a class field) (listView必须成为一个类字段)

  • in the getView of your adapter calculate the distance and set the text to the textView. 在适配器的getView ,计算距离并将文本设置为textView。

In order to optimize the distance calculation you can store the value in the model, but remember to store the Location object as well. 为了优化距离计算,您可以将值存储在模型中,但请记住也要存储Location对象。 In this way you can check, in the future calls, if the Location object has changed. 这样,您可以在以后的调用中检查Location对象是否已更改。 If the Location object changes you need to recalculate the distance, otherwise you can show the last calculated distance. 如果“位置”对象发生更改,则需要重新计算距离,否则可以显示上一次计算的距离。


UPDATE 更新

Remove private String mFormattedDistanceString; 删除private String mFormattedDistanceString; from LocationsAdapter . 来自LocationsAdapter You don't need this, and remove it from the constructor as well. 您不需要它,也可以将其从构造函数中删除。

In your LocationsAdapter you have mLocation , but you never assign it. LocationsAdapter您具有mLocation ,但从未分配它。 Add this method to LocationsAdapter to assign mLocation when it changes in your activity. 将此方法添加到LocationsAdapter以便在您的活动发生更改时分配mLocation。
public void setCurrentLocation(Location lastLocation){ mLocation = lastLocation}

Make listView a field of Locations activity and change onLocationChanged in this way: 使listView成为Locations活动的一个字段,并以这种方式更改onLocationChanged

public void onLocationChanged(Location location) {
    LocationsAdapter adapter = (LocationsAdapter)listView.getAdapter();
    adapter.setCurrentLocation(location);
    adapter.notifyDataSetChanged();
}

create this method in your Word class: 在您的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;
}

In the getView of the adapter, call updateDistance , and than set the TextView text using mFormattedDistanceString of Word 在适配器的getView中,调用updateDistance ,然后使用Word mFormattedDistanceString设置TextView文本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM