2014-02-09 2 views
0

Я пытаюсь создать приложение для Android с тремя вкладками (которое я уже сделал с этим учебником: http://wptrafficanalyzer.in/blog/creating-navigation-tabs-using-tabhost-and-fragments-in-android/, потому что он должен работать на большом количестве устройств), а два из них должны показывать карты.Android Tabs with Maps

Я искал учебники для этого случая, но я не нашел что-то подходящее. Итак, как мне это сделать? Может кто-нибудь, пожалуйста, помогите мне или дайте ссылку, которая объясняет что-то подобное? Надеюсь, на ваш вопрос легко ответить, и я благодарен за каждый ответ.

Update: я пытался что-то сейчас, но так, как я стараюсь не работает: Полный код:

XML:

<TabHost 
xmlns:android="http://schemas.android.com/apk/res/android" 
android:id="@android:id/tabhost" 
android:layout_width="match_parent" 
android:layout_height="match_parent"> 

<LinearLayout 
    android:orientation="vertical" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent"> 

    <TabWidget 
     android:id="@android:id/tabs" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:layout_weight="0"/> 

    <FrameLayout 
     android:id="@android:id/tabcontent" 
     android:layout_width="0dp" 
     android:layout_height="0dp" 
     android:layout_weight="0"/> 

    <FrameLayout 
     android:id="@+id/realtabcontent" 
     android:layout_width="match_parent" 
     android:layout_height="0dp" 
     android:layout_weight="1"/> 

    <FrameLayout 
     android:id="@+id/realtabcontent" 
     android:layout_width="match_parent" 
     android:layout_height="0dp" 
     android:layout_weight="2"/> 

     <fragment 
      android:id="@+id/map" 
      android:layout_width="match_parent" 
      android:layout_height="match_parent" 
      android:layout_below="@id/tv_location" 
      class="com.google.android.gms.maps.SupportMapFragment" 
    /> 
</LinearLayout> 

MainActivity.java:

package com.example.navigationtabdemo; 

import android.os.Bundle; 
import android.support.v4.app.FragmentActivity; 
import android.widget.TabHost; 

public class MainActivity extends FragmentActivity { 
    TabHost tHost; 


@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    tHost = (TabHost) findViewById(android.R.id.tabhost); 
    tHost.setup(); 

    /** Defining Tab Change Listener event. This is invoked when tab is changed */ 
    TabHost.OnTabChangeListener tabChangeListener = new TabHost.OnTabChangeListener() { 

     @Override 
     public void onTabChanged(String tabId) { 
      android.support.v4.app.FragmentManager fm = getSupportFragmentManager(); 
      AndroidFragment androidFragment = (AndroidFragment) fm.findFragmentByTag("android"); 
      AppleFragment appleFragment = (AppleFragment) fm.findFragmentByTag("apple"); 
      MapsFragment mapsFragment = (MapsFragment) fm.findFragmentByTag("maps"); 
      android.support.v4.app.FragmentTransaction ft = fm.beginTransaction(); 

      /** Detaches the androidfragment if exists */ 
      if(androidFragment!=null) 
       ft.detach(androidFragment); 

      /** Detaches the applefragment if exists */ 
      if(appleFragment!=null) 
       ft.detach(appleFragment); 

      /** Detaches the mapsfragment if exists */ 
      if(mapsFragment!=null) 
       ft.detach(mapsFragment); 

      /** If current tab is android */ 
      if(tabId.equalsIgnoreCase("android")){ 

       if(androidFragment==null){ 
        /** Create AndroidFragment and adding to fragmenttransaction */ 
        ft.add(R.id.realtabcontent,new AndroidFragment(), "android"); 
       }else{ 
        /** Bring to the front, if already exists in the fragmenttransaction */ 
        ft.attach(androidFragment); 
       } 

      }else{ /** If current tab is apple */ 
       if(appleFragment==null){ 
        /** Create AppleFragment and adding to fragmenttransaction */ 
        ft.add(R.id.realtabcontent,new AppleFragment(), "apple"); 
       }else{ 
        /** Bring to the front, if already exists in the fragmenttransaction */ 
        ft.attach(appleFragment); 
       } 

      /** }else{ */  /** If current tab is maps */ 
       if(mapsFragment==null){ 
        /** Create MapsFragment and adding to fragmenttransaction */ 
        ft.add(R.id.realtabcontent,new MapsFragment(), "maps"); 
       }else{ 
        /** Bring to the front, if already exists in the fragmenttransaction */ 
        ft.attach(mapsFragment); 
       } 
      } 
      ft.commit(); 
     } 
    }; 

    /** Setting tabchangelistener for the tab */ 
    tHost.setOnTabChangedListener(tabChangeListener); 

    /** Defining tab builder for Android tab */ 
    TabHost.TabSpec tSpecAndroid = tHost.newTabSpec("android"); 
    tSpecAndroid.setIndicator("Android"); 
    tSpecAndroid.setContent(new DummyTabContent(getBaseContext())); 
    tHost.addTab(tSpecAndroid); 

    /** Defining tab builder for Apple tab */ 
    TabHost.TabSpec tSpecApple = tHost.newTabSpec("apple"); 
    tSpecApple.setIndicator("Apple"); 
    tSpecApple.setContent(new DummyTabContent(getBaseContext())); 
    tHost.addTab(tSpecApple); 

    /** Defining tab builder for Maps tab */ 
    TabHost.TabSpec tSpecMaps = tHost.newTabSpec("maps"); 
    tSpecMaps.setIndicator("Maps"); 
    tSpecMaps.setContent(new DummyTabContent(getBaseContext())); 
    tHost.addTab(tSpecMaps); 

} 
} 

DummyTabContent:

package com.example.navigationtabdemo; 

import android.content.Context; 
import android.view.View; 
import android.widget.TabHost.TabContentFactory; 

public class DummyTabContent implements TabContentFactory{ 
    private Context mContext; 

    public DummyTabContent(Context context){ 
     mContext = context; 
    } 

    @Override 
    public View createTabContent(String tag) { 
     View v = new View(mContext); 
     return v; 
    } 
} 

AndroidFragment:

package com.example.navigationtabdemo; 

import android.os.Bundle; 
import android.support.v4.app.ListFragment; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.ArrayAdapter; 
import android.widget.ListView; 

public class AndroidFragment extends ListFragment{ 

    /** An array of items to display in ArrayList */ 
    String android_versions[] = new String[]{ 
     "Jelly Bean", 
     "IceCream Sandwich", 
     "HoneyComb", 
     "Ginger Bread", 
     "Froyo" 
    }; 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 

     /** Creating array adapter to set data in listview */ 
     ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity().getBaseContext(), android.R.layout.simple_list_item_multiple_choice, android_versions); 

     /** Setting the array adapter to the listview */ 
     setListAdapter(adapter); 

     return super.onCreateView(inflater, container, savedInstanceState); 
    } 

    @Override 
    public void onStart() { 
     super.onStart(); 

     /** Setting the multiselect choice mode for the listview */ 
     getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); 
    } 
} 

AppleFragment:

package com.example.navigationtabdemo; 

import android.os.Bundle; 
import android.support.v4.app.ListFragment; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.ArrayAdapter; 
import android.widget.ListView; 

public class AppleFragment extends ListFragment{ 

    /** An array of items to display in ArrayList */ 
    String apple_versions[] = new String[]{ 
     "Mountain Lion", 
     "Lion", 
     "Snow Leopard", 
     "Leopard", 
     "Tiger", 
     "Panther", 
     "Jaguar", 
     "Puma" 
    }; 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 

     /** Creating array adapter to set data in listview */ 
     ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity().getBaseContext(), android.R.layout.simple_list_item_multiple_choice, apple_versions); 

     /** Setting the array adapter to the listview */ 
     setListAdapter(adapter); 

     return super.onCreateView(inflater, container, savedInstanceState); 
    } 

    @Override 
    public void onStart() { 
     super.onStart(); 

     /** Setting the multiselect choice mode for the listview */ 
     getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); 
    } 
} 

MapsFragment.java:

package com.example.navigationtabdemo; 

import android.app.Dialog; 
import android.location.Location; 
import android.os.Bundle; 
import android.support.v4.app.FragmentActivity; 
import android.view.Menu; 
import android.widget.TextView; 

import com.google.android.gms.common.ConnectionResult; 
import com.google.android.gms.common.GooglePlayServicesUtil; 
import com.google.android.gms.maps.CameraUpdateFactory; 
import com.google.android.gms.maps.GoogleMap; 
import com.google.android.gms.maps.GoogleMap.OnMyLocationChangeListener; 
import com.google.android.gms.maps.SupportMapFragment; 
import com.google.android.gms.maps.model.LatLng; 

public class MapsActivity extends FragmentActivity implements OnMyLocationChangeListener { 

GoogleMap googleMap; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    // Getting Google Play availability status 
    int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext()); 

    // Showing status 
    if(status!=ConnectionResult.SUCCESS){ // Google Play Services are not available 
     int requestCode = 10; 
     Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode); 
     dialog.show(); 

    }else { // Google Play Services are available 

     // Getting reference to the SupportMapFragment of activity_main.xml 
     SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map); 

     // Getting GoogleMap object from the fragment 
     googleMap = fm.getMap(); 

     // Enabling MyLocation Layer of Google Map 
     googleMap.setMyLocationEnabled(true); 

     // Setting event handler for location change 
     googleMap.setOnMyLocationChangeListener(this); 

    } 

} 

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.main, menu); 
    return true; 
} 

@Override 
public void onMyLocationChange(Location location) { 
    TextView tvLocation = (TextView) findViewById(R.id.tv_location); 

    // Getting latitude of the current location 
    double latitude = location.getLatitude(); 

    // Getting longitude of the current location 
    double longitude = location.getLongitude(); 

    // Creating a LatLng object for the current location 
    LatLng latLng = new LatLng(latitude, longitude); 

    // Showing the current location in Google Map 
    googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)); 

    // Zoom in the Google Map 
    googleMap.animateCamera(CameraUpdateFactory.zoomTo(15)); 

    // Setting latitude and longitude in the TextView tv_location 
    tvLocation.setText("Latitude:" + latitude + ", Longitude:"+ longitude); 

} 
} 

манифеста:

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
    package="com.example.navigationtabdemo" 
    android:versionCode="1" 
    android:versionName="1.0" > 

<uses-sdk 
    android:minSdkVersion="8" 
    android:targetSdkVersion="16" /> 

<permission 
    android:name="com.example.navigationtabdemo.permission.MAPS_RECEIVE" 
    android:protectionLevel="signature"/> 

<uses-permission android:name="com.example.navigationtabdemo.permission.MAPS_RECEIVE"/> 
<uses-permission android:name="android.permission.INTERNET"/> 
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> 
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/> 
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/> 
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>  

<uses-feature 
    android:glEsVersion="0x00020000" 
    android:required="true"/>  

<application 
    android:allowBackup="true" 
    android:icon="@drawable/ic_launcher" 
    android:label="@string/app_name" 
    android:theme="@style/AppTheme" > 
    <activity 
     android:name="com.example.navigationtabdemo.MainActivity" 
     android:label="@string/app_name" > 
     <intent-filter> 
      <action android:name="android.intent.action.MAIN" /> 

      <category android:name="android.intent.category.LAUNCHER" /> 
     </intent-filter> 
    </activity> 

    <meta-data 
     android:name="com.google.android.maps.v2.API_KEY" 
     android:value="AIzaSyAw4me2T-HBcFiTocAucxdbhVxLD1u3n6g"/>   

</application> 

ответ

0

Это используется, чтобы быть немного сложно сделать, пока MapFragment не вышел. Вам нужно будет заменить свой общий фрагмент на MapFragment. Вам также понадобится ключ API и т. Д., Как если бы вы создали карту с MapActivity. Для получения дополнительной информации ознакомьтесь с руководством разработчика Android Google Maps.

С точки зрения UX карты в закладках могут быть не лучшей идеей. Если вы создадите прокрутки с вкладками, у вас будет два прокручиваемых вида. Если вы этого не сделаете, вы сможете переключать вкладки с помощью кнопок в верхней части экрана.

+0

Я бы воспользовался кнопками, на которые вы все равно нажали, и я уже понял, как использовать карты с его ключом API и т. Д. ... , но как именно я могу использовать картографический фрагмент на вкладках сейчас? – Kon

+0

Почему у MapsFragment.java есть MapsActivity? Ваш фрагмент, который содержит карты, должен расширять MapFragment, а не FragmentActivity. MapFragment является подклассом Fragment и FragmentActivity является подклассом Activity. – LukaCiko

+0

я изменил MapsActivity к MapsFragment, но до сих пор некоторые ошибки, которые, вероятно, easyly фиксированные: XML: Фрагмент: андроид: layout_below = "@ идентификатор/tv_location" MapsFragment.java: общественная пустота: TextView tvLocation = (TextView) findViewById (R .id.tv_location); MainActivity: public void: MapsFragment mapsFragment = (MapsFragment) fm.findFragmentByTag ("карты"); /** Отключает карты, если существует */ if (mapsFragment! = Null) ft.detach (mapsFragment); ft.add (R.id.realtabcontent, новые MapsFragment(), "maps"); ft.attach (mapsFragment); – Kon