Адаптер массива показывает неправильные элементы, которые не могут построить маршрут Google Maps - PullRequest
0 голосов
/ 11 марта 2019

Дай мне ударить мой код прямо здесь ...

public class Index extends AppCompatActivity implements GoogleMap.OnMyLocationButtonClickListener, GoogleMap.OnMyLocationClickListener, OnMapReadyCallback, ActivityCompat.OnRequestPermissionsResultCallback {
    public static String[] account;

    private static final int LOCATION_PERMISSION_REQUEST_CODE = 1;
    private boolean mPermissionDenied = false;
    private GoogleMap mMap;
    String[][] mobileArray = {
            new String[] {"150 Goyeau St, Windsor, ON N9A 6J5","Product 1","N/A","3:30pm"},
            new String[] {"2000 Talbot Road West, Windsor, ON N9A 6S4","Product 2","N/A","4:00pm"},
            new String[] {"350 City Hall Square W, Windsor, ON N9A 6S1","Product 3","N/A","4:30pm"}
    };

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {
            hideSystemUI();
        }
    }
    private void hideSystemUI() {
        View decorView = getWindow().getDecorView();
        decorView.setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_IMMERSIVE
                        | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                        | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_FULLSCREEN);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView tVDriver = (TextView)findViewById(R.id.tVDriver);
        tVDriver.setText(account[0]);
        final TextView tVSpecial = (TextView)findViewById(R.id.tVSpecial);
        final TextView tVProduct = (TextView)findViewById(R.id.tVProduct);
        ArrayAdapter adapter = new ArrayAdapter<String>(this, R.layout.listview, mobileArray[0]);
        ListView listView = (ListView) findViewById(R.id.lVDelivery);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
            @Override
            public void onItemClick(AdapterView<?>adapter, View v, int position, long id){
                tVSpecial.setText(mobileArray[position][2]);
                tVProduct.setText(mobileArray[position][1]);
            }
        });
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }
    @Override
    public void onMapReady(GoogleMap map) {
        mMap = map;
        mMap.setOnMyLocationButtonClickListener(this);
        mMap.setOnMyLocationClickListener(this);
        enableMyLocation();
    }
    private void enableMyLocation() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            PermissionUtils.requestPermission(this, LOCATION_PERMISSION_REQUEST_CODE,
                    Manifest.permission.ACCESS_FINE_LOCATION, true);
        } else if (mMap != null) {
            mMap.setMyLocationEnabled(true);
        }
    }
    @Override
    public boolean onMyLocationButtonClick() {
        Toast.makeText(this, "MyLocation button clicked", Toast.LENGTH_SHORT).show();
        return false;
    }
    @Override
    public void onMyLocationClick(@NonNull Location location) {
        Toast.makeText(this, "Current location:\n" + location, Toast.LENGTH_LONG).show();
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode != LOCATION_PERMISSION_REQUEST_CODE) {
            return;
        }
        if (PermissionUtils.isPermissionGranted(permissions, grantResults,
                Manifest.permission.ACCESS_FINE_LOCATION)) {
            enableMyLocation();
        } else {
            mPermissionDenied = true;
        }
    }
    @Override
    protected void onResumeFragments() {
        super.onResumeFragments();
        if (mPermissionDenied) {
            showMissingPermissionError();
            mPermissionDenied = false;
        }
    }
    private void showMissingPermissionError() {
        PermissionUtils.PermissionDeniedDialog
                .newInstance(true).show(getSupportFragmentManager(), "dialog");
    }
}

Я пытаюсь построить путь на картах Google (и автоматически увеличиваю свое местоположение при загрузке активности.), Коснувшись элемента в массиве.

Проблема в том, что адаптер массива перечисляет первые элементы массивов. Программно это имеет смысл, но это не то, что я хочу. Я хотел отобразить первый элемент во втором массиве для всех первых массивов. Это означает, что я хочу, чтобы в массиве отображался только адрес.

Я знаю, что проблема здесь.

ArrayAdapter adapter = new ArrayAdapter<String>(this, R.layout.listview, mobileArray[0]);

Но какую часть массива я вызываю, чтобы они правильно отображались?

Второй вопрос: как я могу увеличить свое местоположение, когда загружено это действие, и как я могу построить путь? Я попробовал 2 разных способа, и у одного из них были ошибки, которые мешали его работе, а у другого его вообще не отображалось.

Вот мой макет

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:background="@drawable/in_the_weeds"
    android:layout_height="match_parent">

    <include
        layout="@layout/map"
        android:layout_width="match_parent"
        android:layout_height="350dp"
        android:layout_alignParentStart="true"
        android:layout_alignParentBottom="true"
        android:layout_marginStart="0dp"
        android:layout_marginBottom="0dp" />

    <TextView
        android:id="@+id/tVNull"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_marginStart="20dp"
        android:layout_marginTop="25dp"
        android:background="#80FFFFFF"
        android:text="Driver"
        android:textSize="24sp" />

    <TextView
        android:id="@+id/tVDriver"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignParentEnd="true"
        android:layout_marginTop="25dp"
        android:layout_marginEnd="20dp"
        android:background="#80FFFFFF"
        android:text="No Driver"
        android:textSize="24sp"/>

    <ListView
        android:id="@+id/lVDelivery"
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:background="#80FFFFFF"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_marginStart="20dp"
        android:layout_marginTop="90dp" />

    <TextView
        android:id="@+id/tVProductNull"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignParentEnd="true"
        android:layout_marginStart="10dp"
        android:layout_marginTop="90dp"
        android:layout_marginEnd="20dp"
        android:layout_toRightOf="@+id/lVDelivery"
        android:background="#80FFFFFF"
        android:text="Product"
        android:textSize="16sp" />

    <TextView
        android:id="@+id/tVProduct"
        android:layout_width="160dp"
        android:layout_height="165dp"
        android:layout_alignParentTop="true"
        android:layout_alignParentEnd="true"
        android:layout_marginStart="10dp"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="125dp"
        android:layout_marginEnd="20dp"
        android:layout_toRightOf="@+id/lVDelivery"
        android:background="#80FFFFFF"
        android:textSize="24sp"
        android:text="1g - Bubba Hash" />

    <TextView
        android:id="@+id/tVSpecial"
        android:layout_width="match_parent"
        android:layout_height="150dp"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_marginStart="20dp"
        android:layout_marginEnd="20dp"
        android:layout_marginTop="300dp"
        android:layout_toRightOf="@+id/tVProductNull"
        android:background="#80FFFFFF"
        android:textSize="24sp"
        android:text="TextView" />

</RelativeLayout>

1 Ответ

0 голосов
/ 11 марта 2019

Вы можете просто создать новый массив, который содержит только адреса. Но лучшим подходом было бы создание пользовательского класса (назовем его Product), который просто содержит геттеры и сеттеры. Затем вы меняете ArrayAdapter<String> на ArrayAdapter<Product>. Пользовательские ArrayAdapters довольно просты:

https://www.journaldev.com/10416/android-listview-with-custom-adapter-example-tutorial

РЕДАКТИРОВАТЬ: Вот плохое решение, которое я упомянул. Другой набрал бы слишком много времени для печати (но вы должны действительно изучить его, потому что это очень распространенная задача в Android):

public class Index extends AppCompatActivity implements 
GoogleMap.OnMyLocationButtonClickListener, 
GoogleMap.OnMyLocationClickListener, OnMapReadyCallback, 
ActivityCompat.OnRequestPermissionsResultCallback {
public static String[] account;

private static final int LOCATION_PERMISSION_REQUEST_CODE = 1;
private boolean mPermissionDenied = false;
private GoogleMap mMap;
String[][] mobileArray = {
        new String[] {"150 Goyeau St, Windsor, ON N9A 6J5","Product 1","N/A","3:30pm"},
        new String[] {"2000 Talbot Road West, Windsor, ON N9A 6S4","Product 2","N/A","4:00pm"},
        new String[] {"350 City Hall Square W, Windsor, ON N9A 6S1","Product 3","N/A","4:30pm"}
};

String[] addressArray = new String[mobileArray.length];
for (int i=0; i<mobileArray.length; i++) {
    addressArray[i] = mobileArray[0][i];
}


@Override
public void onWindowFocusChanged(boolean hasFocus) {
    super.onWindowFocusChanged(hasFocus);
    if (hasFocus) {
        hideSystemUI();
    }
}
private void hideSystemUI() {
    View decorView = getWindow().getDecorView();
    decorView.setSystemUiVisibility(
            View.SYSTEM_UI_FLAG_IMMERSIVE
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_FULLSCREEN);
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    TextView tVDriver = (TextView)findViewById(R.id.tVDriver);
    tVDriver.setText(account[0]);
    final TextView tVSpecial = (TextView)findViewById(R.id.tVSpecial);
    final TextView tVProduct = (TextView)findViewById(R.id.tVProduct);
    ArrayAdapter adapter = new ArrayAdapter<String>(this, R.layout.listview, addressArray);
    ListView listView = (ListView) findViewById(R.id.lVDelivery);
    listView.setAdapter(adapter);
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
        @Override
        public void onItemClick(AdapterView<?>adapter, View v, int position, long id){
            tVSpecial.setText(mobileArray[position][2]);
            tVProduct.setText(mobileArray[position][1]);
        }
    });
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);
}
@Override
public void onMapReady(GoogleMap map) {
    mMap = map;
    mMap.setOnMyLocationButtonClickListener(this);
    mMap.setOnMyLocationClickListener(this);
    enableMyLocation();
}
private void enableMyLocation() {
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED) {
        PermissionUtils.requestPermission(this, LOCATION_PERMISSION_REQUEST_CODE,
                Manifest.permission.ACCESS_FINE_LOCATION, true);
    } else if (mMap != null) {
        mMap.setMyLocationEnabled(true);
    }
}
@Override
public boolean onMyLocationButtonClick() {
    Toast.makeText(this, "MyLocation button clicked", Toast.LENGTH_SHORT).show();
    return false;
}
@Override
public void onMyLocationClick(@NonNull Location location) {
    Toast.makeText(this, "Current location:\n" + location, Toast.LENGTH_LONG).show();
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    if (requestCode != LOCATION_PERMISSION_REQUEST_CODE) {
        return;
    }
    if (PermissionUtils.isPermissionGranted(permissions, grantResults,
            Manifest.permission.ACCESS_FINE_LOCATION)) {
        enableMyLocation();
    } else {
        mPermissionDenied = true;
    }
}
@Override
protected void onResumeFragments() {
    super.onResumeFragments();
    if (mPermissionDenied) {
        showMissingPermissionError();
        mPermissionDenied = false;
    }
}
private void showMissingPermissionError() {
    PermissionUtils.PermissionDeniedDialog
            .newInstance(true).show(getSupportFragmentManager(), "dialog");
}

}

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...