#android #android-recyclerview #android-mapview
#Android #android-recyclerview #android-mapview
Вопрос:
Мне нужно отобразить в моем RecyclerView некоторые просмотры карт с отображением карты на карте. Итак, я следую некоторому руководству и сделал это в своем RecyclerView:
public class ShowParkAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>
{
private List<Location> locations;
private Context context;
public ShowParkAdapter(List<Location> locations,Context context)
{
this.locations = locations;
this.context = context;
}
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
MapViewListItemView mapViewListItemView = new MapViewListItemView(context);
mapViewListItemView.mapViewOnCreate(null);
ParkAdapter parkHolder = new ParkAdapter(mapViewListItemView);
return parkHolder;
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position)
{
ParkAdapter mHolder = (ParkAdapter)holder;
StringBuilder type, createdAt, stateAt, segnalationAt;
String locate;
Location location = locations.get(position);
mHolder.setmMapViewListItemViewPutMarkers(location.getLatitude(),location.getLongitude(),location.getType());
mHolder.mapViewListItemViewOnResume();
locate = location.getType();
type = new StringBuilder(mHolder.tipologia.getText().toString().trim());
type.append(" ").append(locate);
mHolder.tipologia.setText(type.toString());
createdAt = new StringBuilder(mHolder.data.getText().toString().trim());
createdAt.append(" ").append(location.getCreatedAt());
mHolder.data.setText(createdAt.toString());
stateAt = new StringBuilder(mHolder.state.getText().toString().trim());
stateAt.append(" ").append("verificato");
mHolder.state.setText(stateAt.toString());
segnalationAt = new StringBuilder(mHolder.segnalations.getText().toString().trim());
segnalationAt.append(" ").append("0");
mHolder.segnalations.setText(segnalationAt.toString());
notifyDataSetChanged();
}
public int getItemCount()
{
return locations.size();
}
private class ParkAdapter extends RecyclerView.ViewHolder
{
private MapViewListItemView mMapViewListItemView;
TextView tipologia, data,state,segnalations;
public ParkAdapter(final MapViewListItemView mapViewListItemView)
{
super(mapViewListItemView);
mMapViewListItemView = mapViewListItemView;
tipologia = (TextView)mapViewListItemView.findViewById(R.id.type);
data = (TextView)mapViewListItemView.findViewById(R.id.addedAt);
state = (TextView)mapViewListItemView.findViewById(R.id.state);
segnalations = (TextView)mapViewListItemView.findViewById(R.id.signal);
state.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showErrorMessage(context,mapViewListItemView.getResources().getString(R.string.infoStato));
}
});
segnalations.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showErrorMessage(context,mapViewListItemView.getResources().getString(R.string.infoSign));
}
});
}
private void showErrorMessage(Context mContext,String message)
{
new AlertDialog.Builder(mContext)
.setMessage(message)
.setCancelable(false)
.setPositiveButton("Ok", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
}
}).create().show();
}
public void setmMapViewListItemViewPutMarkers(double latitude, double longitude,String type)
{
if(mMapViewListItemView != null)
mMapViewListItemView.putMarkers(latitude,longitude,type);
}
public void mapViewListItemViewOnCreate(Bundle savedInstanceState) {
if (mMapViewListItemView != null) {
mMapViewListItemView.mapViewOnCreate(savedInstanceState);
Log.d("map","oncreate");
}
}
public void mapViewListItemViewOnResume() {
if (mMapViewListItemView != null) {
mMapViewListItemView.mapViewOnResume();
Log.d("map","onresume");
}
}
public void mapViewListItemViewOnPause() {
if (mMapViewListItemView != null) {
mMapViewListItemView.mapViewOnPause();
Log.d("map","onpause");
}
}
public void mapViewListItemViewOnDestroy() {
if (mMapViewListItemView != null) {
mMapViewListItemView.mapViewOnDestroy();
Log.d("map","ondestroy");
}
}
public void mapViewListItemViewOnLowMemory() {
if (mMapViewListItemView != null) {
mMapViewListItemView.mapViewOnLowMemory();
}
}
public void mapViewListItemViewOnSaveInstanceState(Bundle outState) {
if (mMapViewListItemView != null) {
mMapViewListItemView.mapViewOnSaveInstanceState(outState);
}
}
}
}
но, когда я показываю результат, я получаю эту ошибку:
Я пытаюсь использовать notifyDataSetChanged();
, но я даю те же ошибки. Как я мог решить эту проблему? Спасибо
Комментарии:
1. Как я мог решить эту проблему? анализируя ваш … вы добавляете новый текст к старому при каждом повторном использовании представления… это вообще не имеет смысла
2. итак, вы гениальны! и где я добавляю новый текст к старому?
3. Вы вообще понимаете свой код… пожалуйста, используйте утку отладки и объясните ей построчно
4. @Selvin Я также меняю Stringbuilder как: mHolder.tipologia.setText(тип. toString()); но он продолжает добавлять строки .. как я мог сделать, чтобы избежать добавления при завершении recyclerview?
Ответ №1:
Я думаю, что ошибка здесь:
type = new StringBuilder(mHolder.tipologia.getText().toString().trim());
type.append(" ").append(locate);
mHolder.tipologia.setText(type.toString());
RecyclerView
будет ли повторно использоваться представление. И здесь вы берете предыдущий текст и добавляете что-то. Итак, когда a View
перерабатывается, вы добавляете новые данные к старым данным.
Вы можете изменить что-то вроде:
type = new StringBuilder("Base text: ");
type.append(locate);
mHolder.tipologia.setText(type.toString());
Или просто:
mHolder.tipologia.setText("Base text: " type.toString());
И с помощью intl:
mHolder.tipologia.setText(context.getString(R.string.my_base_text) type.toString());
PS: то же самое для других текстов
Комментарии:
1. Я пробую ваше решение.. ранее я понимал, что StringBuilder не может добавить новую строку в предыдущую…
2. У меня такая же проблема… Я использую ваше решение, но оно продолжает добавлять другую строку
3. наконец-то я решаю проблему, вы даете мне хорошую идею, спасибо!