从另一个开始片段 - >可能我的应用程序启动了错误的方式?

时间:2013-10-14 16:48:45

标签: android android-activity fragment

我已经开始构建一个应用程序,但我想我可能在主结构中做错了。我的应用程序是3个片段,彼此通信。第一个片段是关于设置,第二个是可扩展的数组列表。第三个是Gmap。

单击第一个片段中的特定设置(即位置)将使gmap在好位置打开...第二个片段中的子项目相同。 我还希望有一个线程来更新所有片段的当前位置。

这就是,我不知道应该如何构建我的应用程序。有3个片段是否好,我应该使用3个活动吗?如何在片段内进行沟通?我读到片段不应该直接通信在一起,但在我的情况下,我不知道可扩展数组列表的子代如何不能直接打开包含GMap的片段......

这是一张图片,只是想弄清楚我的应用会是什么样子:

http://s14.postimg.org/ywj7yu8qp/Untitled.png

到目前为止,这是代码:

MainActivity:

package com.stylingandroid.basicactionbar;



import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends Activity
{
    private class MyTabListener implements ActionBar.TabListener
    {
        private Fragment mFragment;
        private final Activity mActivity;
        private final String mFragName;

        public MyTabListener( Activity activity, String fragName )
        {
            mActivity = activity;
            mFragName = fragName;
        }

        @Override
        public void onTabReselected( Tab tab, FragmentTransaction ft )
        {
            // TODO Auto-generated method stub

        }

        @Override
        public void onTabSelected( Tab tab, FragmentTransaction ft )
        {
            mFragment = Fragment.instantiate( mActivity, mFragName );
            ft.add( android.R.id.content, mFragment );
        }

        @Override
        public void onTabUnselected( Tab tab, FragmentTransaction ft )
        {
            ft.remove( mFragment );
            mFragment = null;
        }
    }

    @Override
    public void onCreate( Bundle savedInstanceState )
    {
        super.onCreate( savedInstanceState );       
//      Intent intent;

        ActionBar ab = getActionBar();
        ab.setNavigationMode( ActionBar.NAVIGATION_MODE_TABS );

        Tab tab = ab.newTab()
                .setText( R.string.title_param )
                .setTabListener( 
                        new MyTabListener( this, 
                                Param.class.getName() ) );
        ab.addTab( tab );

//      intent = new Intent().setClass(this, Friends.class);
        tab = ab.newTab()
                .setText( R.string.title_friends )


                .setTabListener( 
                        new MyTabListener( this, 
                                Friends.class.getName() ) );
        ab.addTab( tab );

        tab = ab.newTab()
                .setText( R.string.title_maps )
                .setTabListener( 
                        new MyTabListener( this, 
                                Maps.class.getName() ) );
        ab.addTab( tab );
    }

    @Override
    public boolean onCreateOptionsMenu( Menu menu )
    {
        getMenuInflater().inflate( R.menu.main, menu );
        return true;
    }

    @Override
    public boolean onOptionsItemSelected( MenuItem item )
    {
        boolean ret;
        if (item.getItemId() == R.id.menu_settings)
        {
            // Handle Settings
            ret = true;
        } else
        {
            ret = super.onOptionsItemSelected( item );
        }
        return ret;
    }
}

TAB1:

package com.stylingandroid.basicactionbar;




import java.io.IOException;
import java.util.List;
import java.util.Locale;

import android.app.Fragment;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class Param extends Fragment
{

    Button btnShowLocation;
    private View V;
    TextView text;
    public static double latitude;
    public static double longitude;

    // GPSTracker class
    GPSTracker gps;
    @Override
    public View onCreateView( LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState )
    {
        V = inflater.inflate( R.layout.param, container, false );

        gps = new GPSTracker(getActivity());
        if(gps.canGetLocation()){
            text = (TextView) V.findViewById(R.id.widget35);


                latitude = gps.getLatitude();
                longitude = gps.getLongitude();
                    String cityName=null;                 
                    Geocoder gcd = new Geocoder(getActivity(), Locale.getDefault());                 
                    List<Address>  addresses;  
                try {  
                     addresses = gcd.getFromLocation(latitude, longitude, 1);  
                     if (addresses.size() > 0)  
                      System.out.println(addresses.get(0).getLocality());  
                     cityName=addresses.get(0).getLocality();  

                    } catch (IOException e) {
                     e.printStackTrace();  
                    } 
                // create class object

                // check if GPS enabled     
                    text.setText(cityName);

                }else{
                    // can't get location
                    // GPS or Network is not enabled
                    // Ask user to enable GPS/network in settings
                    gps.showSettingsAlert();
                }



        return V;
    }
}

TAB2:

package com.stylingandroid.basicactionbar;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import android.app.Fragment;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.Toast;

public class Friends extends Fragment implements OnChildClickListener
{
    private static List<Country> Countries;
    private ExpandableListView expandableListView;
    private CountryAdapter adapter;
    private View V;


    @Override
    public View onCreateView( LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState )
    {
       V = inflater.inflate( R.layout.frag2, container, false );
        expandableListView = (ExpandableListView) V.findViewById(R.id.expandableListView);
        expandableListView.setOnChildClickListener(this);
        LoadCountries();

        return V;
    }


    private void LoadCountries() {
        Countries = new ArrayList<Country>();

        ArrayList<String> citiesAustralia = new ArrayList<String>(
                Arrays.asList("Brisbanea", "Hobart", "Melbourne", "Sydney"));
        Countries.add(new Country("Australia", citiesAustralia));

        ArrayList<String> citiesChina = new ArrayList<String>(
                Arrays.asList("Beijing", "Chuzhou", "Dongguan", "Shangzhou"));
        Countries.add(new Country("China", citiesChina));
        adapter = new CountryAdapter(getActivity(), Countries);
        expandableListView.setAdapter(adapter);

       }

    @Override
    public boolean onChildClick(ExpandableListView arg0, View arg1, int arg2,
            int arg3, long arg4) {


/*      Fragment param = new Param();
        android.app.FragmentTransaction ft  = getFragmentManager().beginTransaction();
        ft.replace(R.id.frag2, param);
        ft.addToBackStack(null);
        ft.commit();

        */
        Toast.makeText(getActivity(), "Clicked on Detail " , Toast.LENGTH_LONG).show();
        return true;
    }

}

TAB3:

package com.stylingandroid.basicactionbar;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

import android.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class Maps extends Fragment
{
    static final LatLng HAMBURG = new LatLng(Param.latitude, Param.longitude);
    static final LatLng KIEL = new LatLng(53.551, 9.993);
    private GoogleMap map;
    View V;
    @Override
    public View onCreateView( LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState )
    {
        V = inflater.inflate( R.layout.frag1, container, false );

        map = ((MapFragment) getActivity().getFragmentManager().findFragmentById(R.id.map))
                .getMap();


            Marker hamburg = map.addMarker(new MarkerOptions().position(HAMBURG)
                    .title("Hamburg"));

            // Move the camera instantly to hamburg with a zoom of 15.
            map.moveCamera(CameraUpdateFactory.newLatLngZoom(HAMBURG, 15));

            // Zoom in, animating the camera.
            map.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);

            GoogleMap gMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();

            gMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
            gMap.setMyLocationEnabled(true);
            gMap.getUiSettings().setCompassEnabled(true);
            Log.e("Maps", "------EOC-------");



            return V;

          }





    }

param.xml(tab1):

<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout
    android:id="@+id/widget0"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    xmlns:android="http://schemas.android.com/apk/res/android">
<ToggleButton
    android:id="@+id/widget33"
    android:layout_width="125dp"
    android:layout_height="59dp"
    android:textOn="I&apos;m free!"
    android:textOff="I&apos;m free!"
    android:layout_x="78dp"
    android:layout_y="29dp" />
<TextView
    android:id="@+id/widget34"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Lieu actuel"
    android:layout_x="87dp"
    android:layout_y="196dp" />
<TextView
    android:id="@+id/widget35"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Indisponible"
    android:layout_x="101dp"
    android:layout_y="247dp" />
<TextView
    android:id="@+id/widget36"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="GPS"
    android:layout_x="89dp"
    android:layout_y="108dp" />
<ToggleButton
    android:id="@+id/widget37"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textOn="On"
    android:textOff="Off"
    android:layout_x="158dp"
    android:layout_y="99dp" />

</AbsoluteLayout>

frag2.xml(tab2):

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent">
    <ExpandableListView
            android:id="@+id/expandableListView"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"/>
</LinearLayout>

frag1.xml(tab3):

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

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

</RelativeLayout>

以下只是主要片段,如果需要,我还可以提供所有类的完整代码......

问题:

关于片段如何工作,我开始做的还可以吗?我应该改为使用活动吗?我可以继续创建片段吗?我是否尊重编程标准? 如何从片段到另一个片段进行通信?我使用全局变量,所以当更新某些内容时,gmap(tab3)也会更新,但我没有看到如何在点击时打开gmap片段。

当我在gmap标签上点击两次时,gmap正在使应用程序崩溃......?

非常感谢你们。

1 个答案:

答案 0 :(得分:0)

您可以使用所需的所有片段:)

我认为最好的方法是创建一个抽象类来保存和处理所有数据和事件。

在抽象类中声明方法静态,以便您可以直接在类上调用它们。