#java #android #android-intent #mapbox
#java #Android #android-намерение #mapbox
Вопрос:
Я хотел бы выбрать несколько игроков (выделенных фиолетовыми цветами, т.Е. Игрока 1, игрока 3 и игрока 5) из «MyPlayerActivity» и добавить этих выбранных игроков на карту mapbox в качестве маркеров (MainActivity) при нажатии на кнопку «Добавить игрока». Может кто-нибудь, пожалуйста, помогите мне, как этого добиться?
Ниже приведен мой код MyPlayerActivity
public class MyPlayerActivity extends ListActivity {
private static int lastClickId = -1;
// Array of strings storing country names
String[] players = new String[] {
"Player 1",
"Player 2",
"Player 3",
"Player 4",
"Player 5"
};
// Array of integers points to images stored in /res/drawable-ldpi/
int[] images = new int[]{
R.drawable.play_1,
R.drawable.play_2,
R.drawable.play_3,
R.drawable.play_4,
R.drawable.play_5
};
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_view);
final ListView listView = (ListView) findViewById(android.R.id.list);
View headerView = ((LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.header, null, false);
getListView().addHeaderView(headerView);
// Each row in the list stores country name, currency and flag
List<HashMap<String,String>> aList = new ArrayList<HashMap<String,String>>();
for(int i=0;i<6;i ){
HashMap<String, String> hm = new HashMap<String,String>();
hm.put("label", "" players[i]);
hm.put("imgs", Integer.toString(images[i]) );
aList.add(hm);
}
// Keys used in Hashmap
String[] from = { "imgs","label"};
// Ids of views in listview_layout
int[] to = { R.id.imgs,R.id.label};
// Instantiating an adapter to store each items
// R.layout.listview_layout defines the layout of each item
SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), aList, R.layout.list_view, from, to);
// Getting a reference to listview of main.xml layout file
// Setting the adapter to the listView
listView.setAdapter(adapter);
// Item Click Listener for the listview
AdapterView.OnItemClickListener itemClickListener = new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View container, int position, long id) {
// Getting the Container Layout of the ListView
RelativeLayout relativeLayoutParent = (RelativeLayout) container;
//LinearLayout linearLayoutParent = (LinearLayout) container;
RelativeLayout relativeLayoutChild = (RelativeLayout) relativeLayoutParent.getChildAt(1);
// Getting the inner Linear Layout
// LinearLayout linearLayoutChild = (LinearLayout ) linearLayoutParent.getChildAt(1);
// Getting the Player TextView
TextView myPlayer = (TextView) relativeLayoutChild.getChildAt(0);
Toast.makeText(getBaseContext(), myPlayer.getText().toString(), Toast.LENGTH_SHORT).show();
}
};
// Setting the item click listener for the listview
listView.setOnItemClickListener(itemClickListener);
}
}
Following is the list_view.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<ImageView
android:id="@ id/imgs"
android:layout_width="75dp"
android:layout_height="75dp"
android:paddingTop="10dp"
android:paddingStart="10dp"
android:paddingEnd="10dp"
android:paddingRight="10dp"
android:paddingBottom="10dp" >
</ImageView>
<TextView
android:id="@ id/label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_centerVertical="true"
android:text="@ id/label"
android:textSize="17sp" >
</TextView>
<Button
android:id="@ id/button2"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginBottom="10dp"
android:text="@string/Add_Player"
android:background="#66ccff"
android:textColor="#ffffff">
</Button>
<ListView android:id="@id/android:list"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
Below is the 'MainActivity' code, where I have initialized my map and this is where I would need to add my Player markers and display in mapbox map.
'MainActivity' code where I have initialized my map:
public class MainActivity extends AppCompatActivity implements ActivityCompat.OnRequestPermissionsResultCallback {
private MapView mapView;
private MapboxMap map;
private Marker customMarker;
private ListView mDrawerList;
private DrawerLayout mDrawerLayout;
private ArrayAdapter<String> mAdapter;
private ActionBarDrawerToggle mDrawerToggle;
private String mActivityTitle;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MapboxAccountManager.start(this, "token");
final boolean permissionGranted = ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED;
setContentView(R.layout.activity_main);
mDrawerList = (ListView)findViewById(R.id.navList);
mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
mActivityTitle = getTitle().toString();
onMapReady(map);
addDrawerItems();
setupDrawer();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
mapView = (MapView) findViewById(R.id.mapview);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(MapboxMap mapboxMap) {
Log.i("MapAsync", " is called");
//you need to initialize 'map' with 'mapboxMap';
map = mapboxMap;
//map.setOnMapLongClickListener(new LatLng);
map.setOnMapLongClickListener(new MapboxMap.OnMapLongClickListener() {
@Override
public void onMapLongClick(@NonNull LatLng point) {
if (customMarker != null) {
// Remove previous added marker
map.removeAnnotation(customMarker);
customMarker = null;
}
customMarker = map.addMarker(new MarkerOptions()
.title("Custom Marker")
.snippet(new DecimalFormat("#.#####").format(point.getLatitude()) ", "
new DecimalFormat("#.#####").format(point.getLongitude()))
.position(point));
}
}); // Long click Ends here
}
});
}
// Initialize the onMapReady
public void onMapReady(@NonNull MapboxMap mapboxMap) {
this.map = mapboxMap;
}
private void addDrawerItems() {
String[] osArray = { "Map", "Players", "Video", "TestPlayer", "My Profile"};
mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, osArray);
mDrawerList.setAdapter(mAdapter);
mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// depending on the position in your drawer list change this
switch (position) {
case 0: {
Toast.makeText(MainActivity.this, "Access map", Toast.LENGTH_SHORT).show();
break;
}
case 1:{
Intent intent = new Intent(MainActivity.this, ListPlayerActivity.class);
startActivity(intent);
Toast.makeText(MainActivity.this, "See players arena", Toast.LENGTH_SHORT).show();
break;
}
case 2:{
Intent appIntent = new Intent(MainActivity.this, PlayYoutubeActivity.class);
startActivity(appIntent);
Toast.makeText(MainActivity.this, "See Video", Toast.LENGTH_SHORT).show();
break;
}
case 3:{
Intent appIntent = new Intent(MainActivity.this, MyPlayerActivity.class);
startActivity(appIntent);
Toast.makeText(MainActivity.this, "Test to see my players", Toast.LENGTH_SHORT).show();
break;
}
default:
break;
}
Toast.makeText(MainActivity.this, "More details to follow", Toast.LENGTH_SHORT).show();
}
});
}
private void setupDrawer() {
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close) {
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getSupportActionBar().setTitle("Navigation!");
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getSupportActionBar().setTitle(mActivityTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
mDrawerToggle.setDrawerIndicatorEnabled(true);
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
// Activate the navigation drawer toggle
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
// Add the mapView lifecycle to the activity's lifecycle methods
@Override
public void onResume() {
super.onResume();
mapView.onResume();
}
@Override
public void onPause() {
super.onPause();
mapView.onPause();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
public class TelemetryServiceNotConfiguredException extends RuntimeException {
public TelemetryServiceNotConfiguredException() {
super("nTelemetryService is not configured in your applications AndroidManifest.xml. "
"nPlease add "com.mapbox.mapboxsdk.telemetry.TelemetryService" service in your applications AndroidManifest.xml"
"nFor an example visit For more information visit https://www.mapbox.com/android-sdk/.");
}
}
}
Ответ №1:
Чтобы добавить маркер на карту, вы можете использовать этот фрагмент:
mapboxMap.addMarker(new MarkerViewOptions()
.position(new LatLng(<position of player>)));
Если listview и map находятся в отдельных действиях, вы можете передать информацию о выбранном игроке в действие карты, используя намерение. Это то, что вы искали?
Комментарии:
1. Как мы можем получить выбранные имена игроков из списка и передать намерение
2. ListView.setOnItemClickListener(новый AdapterView. OnItemClickListener() { @override общественного недействительными onItemClick(AdapterView<?> родитель, вид Вид, внутр позиция, длинный идентификатор) { намерение намерение = новый намерение(MyPlayerActivity.это, MainActivity.class); намерение.putExtra(«идентификатор»,идентификатор); startActivity(намерение); } });