2

Im creating an app that there's a map above and listview of countries below. When the user click a data in list, the layout with list will be replace and be the profile of the country and the map above will stick. Can you suggest a way to overrite the layout of list and replace it with the profile of country. The linearlayout with id=layout will replace by a layout composed of the profile of the country

MainActivity

public class MainActivity extends AppCompatActivity implements LocationListener {

    GoogleMap map;

    List<CountryModel> GetCountry;
    Context context = this;
    DatabaseHelper dbhelper;
    DatabaseHelper db = new DatabaseHelper(this);
    ListView lv;

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

        dbhelper = new DatabaseHelper(MainActivity.this);

        try{
            dbhelper.createDataBase();
        }
        catch(IOException e){
            e.printStackTrace();
        }
        try {
            dbhelper.openDataBase();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        GetCountry = dbhelper.getCountry();
        lv = (ListView) findViewById(R.id.listView);
        lv.setAdapter(new ViewAdapter());

        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                LatLng latlngtofocus = new LatLng(Double.parseDouble(GetCountry.get(i).getlatitude()),  Double.parseDouble(GetCountry.get(i).getlongitude()));

                map.animateCamera(CameraUpdateFactory.newLatLngZoom(latlngtofocus, 17.0f));

                MarkerOptions markerOptions = new MarkerOptions();
                markerOptions.position(latlngtofocus);
                //adding marker to the map
                map.addMarker(markerOptions);




            }
        });



        //To get MapFragment reference from xml layout
        MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.map);

        //To get map object
        map = mapFragment.getMap();
        map.getUiSettings().setZoomControlsEnabled(true);

       /* //to show current location in the map
        map.setMyLocationEnabled(true);

        map.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {

                Toast.makeText(getApplicationContext(), latLng.toString(), Toast.LENGTH_LONG).show();
            }
        });*/

        //To setup location manager
        LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        //To request location updates
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1, 1, this);

    }


    @Override
    public void onLocationChanged(Location location) {

        //To clear map data
        map.clear();

        //To hold location
        LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());

        //To create marker in map
        MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.position(latLng);
        markerOptions.title("My Location");
        //adding marker to the map
        map.addMarker(markerOptions);

        //opening position with some zoom level in the map
        map.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 17.0f));
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }

    /****************************************************************************************
     *                                      CUSTOM LIST
     ****************************************************************************************/
    public class ViewAdapter extends BaseAdapter {

        LayoutInflater mInflater;

        public ViewAdapter() {
            mInflater = LayoutInflater.from(context);
        }

        @Override
        public int getCount() {
            return GetCountry.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {

            if (convertView == null) {
                convertView = mInflater.inflate(R.layout.item_country,null);
            }

            final TextView country = (TextView) convertView.findViewById(R.id.country);
            final TextView latitude = (TextView) convertView.findViewById(R.id.latitude);
            final TextView longitude = (TextView) convertView.findViewById(R.id.longitude);

            country.setText(GetCountry.get(position).getcountry());
            latitude.setText(GetCountry.get(position).getlatitude());
            longitude.setText(GetCountry.get(position).getlongitude());

            return convertView;
        }
    }
}

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:map="http://schemas.android.com/apk/res-auto"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

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

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/layout">

    <ListView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/listView"
        android:layout_gravity="center_horizontal" />

    </LinearLayout>

</LinearLayout>

EDITED MAIN ACTIVITY

public class MainActivity extends AppCompatActivity implements LocationListener {

    GoogleMap map;

    List<CountryModel> GetCountry;
    Context context = this;
    DatabaseHelper dbhelper;
    DatabaseHelper db = new DatabaseHelper(this);
    ListView lv;
    View yourListView,yourProfileView;



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

        dbhelper = new DatabaseHelper(MainActivity.this);

        try{
            dbhelper.createDataBase();
        }
        catch(IOException e){
            e.printStackTrace();
        }
        try {
            dbhelper.openDataBase();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        GetCountry = dbhelper.getCountry();
        lv = (ListView) findViewById(R.id.listView);
        lv.setAdapter(new ViewAdapter());

        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                LatLng latlngtofocus = new LatLng(Double.parseDouble(GetCountry.get(i).getlatitude()),  Double.parseDouble(GetCountry.get(i).getlongitude()));

                map.animateCamera(CameraUpdateFactory.newLatLngZoom(latlngtofocus, 17.0f));

                MarkerOptions markerOptions = new MarkerOptions();
                markerOptions.position(latlngtofocus);
                //adding marker to the map
                map.addMarker(markerOptions);


                View yourListView = findViewById(R.id.layout);
                ViewGroup parent = (ViewGroup) yourListView.getParent();
                parent.removeView(yourListView);
                // inflate your profile view (or get the reference to it if it's already inflated)
                View yourProfileView = getLayoutInflater().inflate(R.layout.profile_country, parent, false);
                // add it to the parent
                parent.addView(yourProfileView);

            }


        });



        //To get MapFragment reference from xml layout
        MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.map);

        //To get map object
        map = mapFragment.getMap();
        map.getUiSettings().setZoomControlsEnabled(true);

       /* //to show current location in the map
        map.setMyLocationEnabled(true);

        map.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {

                Toast.makeText(getApplicationContext(), latLng.toString(), Toast.LENGTH_LONG).show();
            }
        });*/

        //To setup location manager
        LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        //To request location updates
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1, 1, this);

    }


    @Override
    public void onLocationChanged(Location location) {

        //To clear map data
        map.clear();

        //To hold location
        LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());

        //To create marker in map
        MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.position(latLng);
        markerOptions.title("My Location");
        //adding marker to the map
        map.addMarker(markerOptions);

        //opening position with some zoom level in the map
        map.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 17.0f));
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }

    /****************************************************************************************
     *                                      CUSTOM LIST
     ****************************************************************************************/
    public class ViewAdapter extends BaseAdapter {

        LayoutInflater mInflater;

        public ViewAdapter() {
            mInflater = LayoutInflater.from(context);
        }

        @Override
        public int getCount() {
            return GetCountry.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {

            if (convertView == null) {
                convertView = mInflater.inflate(R.layout.item_country,null);
            }

            final TextView country = (TextView) convertView.findViewById(R.id.country);
            final TextView latitude = (TextView) convertView.findViewById(R.id.latitude);
            final TextView longitude = (TextView) convertView.findViewById(R.id.longitude);

            country.setText(GetCountry.get(position).getcountry());
            latitude.setText(GetCountry.get(position).getlatitude());
            longitude.setText(GetCountry.get(position).getlongitude());

            return convertView;
        }
    }

    @Override
    public void onBackPressed() {
        if(yourProfileView != null && yourProfileView.getVisibility() == View.VISIBLE) {
            // remove your profile view
            ViewGroup parent = (ViewGroup) yourListView.getParent();
            parent.removeView(yourProfileView);

            // a reference to yourListView has to be saved somewhere; just get it

            // add your listview to the parent
            parent.addView(yourListView);
        } else {
            super.onBackPressed();
        }
    }

}

4 Answers 4

4

Probably the simplest way is to replace one view with another:

// remove your listview
View yourListView = findViewById(R.id.listview);
ViewGroup parent = (ViewGroup) yourListView.getParent();
parent.removeView(yourListView);
// inflate your profile view (or get the reference to it if it's already inflated)
View yourProfileView = getLayoutInflater().inflate(R.layout.profile_view, parent, false);
// add it to the parent
parent.addView(yourProfileView);

Another way is to use fragments. See Kalem's answer

Edit

For your situation the best way is to use fragments, but if you're extremely low on time, try something like this:

@Override
public void onBackPressed() {
    if(yourProfileView != null && yourProfileView.getParent() != null) {
        // remove your profile view
        ViewGroup parent = (ViewGroup) yourProfileView.getParent();
        parent.removeView(yourProfileView);

        // a reference to yourListView has to be saved somewhere; just get it

        // add your listview to the parent
        parent.addView(yourListView);
    } else {
        super.onBackPressed();
    }
}
Sign up to request clarification or add additional context in comments.

23 Comments

your code is working thank you but why the app closes when i press cancel button?it doesnt go back to the listview. okay thanks for the suggestion ill study fragment soon but for the meantime, ill use the code that you suggest since im in a hurry
but sir why is it closes it doesnt go back to the previous listview when im in profile layout and when i press cancel button?
btw sir im using the cancel of the phone,not the button inside the layout
This is a heavy solution if you are removing and adding the views each time an list item is click. I'll go for visibility changes if you want to do something like this or use @mikeD 's approch (never use it but looks good).
didnt get it sir sorry. can u please apply the condtion based from your code.sorry newbie only
|
2

There is a nice class that helps you with switching between 2 layouts called ViewSwitcher

You're layout could look like this:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:map="http://schemas.android.com/apk/res-auto"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

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

  <ViewSwitcher
      android:layout_width="wrap_content"
      android:layout_height="match_parent"
      android:id="@+id/viewSwitcher">

    <ListView
        android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal" />

    <FrameLayout
        android:id="@+id/profile_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        >

      <!-- Detailed fields here -->

    </FrameLayout>

  </ViewSwitcher>

</LinearLayout>

When you click an element on the list you call viewSwitcher.showNext(). If you want to get back to list u call it again. Hope it helps.

Comments

2

Have you tried using 2 Fragment ? Where Your ListView with your contries list is the first one and the detail of the country is the second one. You can then show/hide fragments as you please (in you case hide ListView fragment when item is selected and show the details one).


Edit : as the OP is looking for other alternatives :

Other solution is to play with views visibility. You don't really need to remove the ListView from the layout you just need to hide it while the country details are shown. So set your layout to have a FrameLayout containing you ListView and the View with the details of the country. Set the details view visibility to gone by default, and when you select an element on the list set it to visible. Add the inverse behaviour onBackPressed() when the ListView visibility is gone.

But if i were you i still go for fragments.

3 Comments

im not familiar with fragment yet since im new to android. is that the only way?btw thanks for the suggestion. if fragment is the only way, then ill study it
Is not the only way but is a neat one and you can easily animate fragments transitions. Besides you are already using a fragment even if it's not made by you (MapFragment) ;)
yeah since i saw it in google :) thanks btw ill study fragment
0

Add One more Fragment to show Profile. When clicking listview, load the information to Fragment components.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.