Android将线性布局替换为xml中的另一个线性布局



我正在创建一个应用程序,上面有地图,下面有国家的列表视图。当用户点击列表中的数据时,带有列表的布局将被替换为该国家的概况,上面的地图将被粘贴。你能建议一种方法来高估列表的布局,并用国家的概况代替它吗。id=布局的linearlayout将被由国家的配置文件组成的布局所取代

主要活动

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>

编辑的主要活动

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();
        }
    }
}

可能最简单的方法是用另一个视图替换一个视图:

// 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);

另一种方法是使用碎片。查看Kalem的答案

编辑

对于你的情况,最好的方法是使用碎片,但如果你的时间非常短,可以尝试这样的方法:

@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();
    }
}

有一个很好的类可以帮助您在两个布局之间切换,称为ViewSwitcher

你的布局可能看起来像这样:

<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>

当你点击列表上的一个元素时,你会调用viewSwitcher.showNext()。如果你想回到列表,你会再次调用它。希望能有所帮助。

您尝试过使用2 Fragment吗?Where Your ListView和你的悔过清单是第一个,国家的详细信息是第二个。然后,您可以随意显示/隐藏片段(在您的情况下,当项目被选中时,隐藏ListView片段,并显示详细信息)。


编辑:因为OP正在寻找其他替代方案:

另一种解决方案是利用视图可见性。您不需要从布局中删除ListView,只需要在显示国家/地区详细信息时将其隐藏即可。因此,将您的布局设置为FrameLayout,其中包含ListView和包含国家详细信息的视图。默认情况下,将详细信息视图的可见性设置为"消失",当您在列表中选择某个图元时,将其设置为"可见"。当ListView可见性消失时,添加相反的行为onBackPressed()

但如果我是你,我仍然会去寻找碎片。

再添加一个片段以显示配置文件。单击listview时,将信息加载到Fragment组件中。

最新更新