为什么我的片段与主要活动重叠?我正在使用包含一些片段的滑动菜单。我在我的主要活动中有一些主要功能,但是当我尝试单击菜单时,而不是替换主要活动布局,它会出现在主要活动的顶部。
问题: issue link
mainActivity:
package com.blueflair.incre;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;
import org.apache.http.HttpException;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.net.ssl.HttpsURLConnection;
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
public static final String SERVER_ADDRESS = "http://192.168.0.1/serverfiles/userGPS.php";
DrawerLayout drawerLayout;
ListView drawerList;
ActionBarDrawerToggle drawerListener;
ActionBar actionBar;
Toolbar toolbar;
MyAdapter adapter;
LocalUserData userLocalStore;
float lastTranslate = 0.0f;
LocationManager lm;
Location location;
double longitude, latitude;
ProgressDialog progressDialog;
HashMap<String, String> postDataParams = new HashMap<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mainactivity_layout);
userLocalStore = new LocalUserData(this);
toolbar = (Toolbar) findViewById(R.id.tool_bar);
setSupportActionBar(toolbar);
actionBar = getSupportActionBar();
if(actionBar != null) {
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM | ActionBar.DISPLAY_SHOW_HOME | ActionBar.DISPLAY_HOME_AS_UP);
}
drawerList = (ListView) findViewById(R.id.drawerList);
adapter = new MyAdapter(this);
drawerList.setAdapter(adapter);
drawerList.setOnItemClickListener(new SlideMenuClickListener());
final FrameLayout frame = (FrameLayout) findViewById(R.id.mainContent);
if(!isLocationEnabled(this)) {
displayPromptForEnablingGPS(this);
} else {
//Get the user's location latitude and longitude
lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location!=null){
latitude = location.getLatitude();
longitude = location.getLongitude();
userLocalStore.setUserLocation(longitude, latitude);
new StoreUserLocationAsyncTask().execute();
} else {
Toast.makeText(this, "Problem in getting your location. Please try again later", Toast.LENGTH_SHORT).show();
}
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 10, locationListener);
}
drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
drawerListener = new ActionBarDrawerToggle(this, drawerLayout ,R.string.drawer_open, R.string.drawer_close) {
@SuppressLint("NewApi")
public void onDrawerSlide(View drawerView, float slideOffset) {
float moveFactor = (drawerList.getWidth() * slideOffset);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
frame.setTranslationX(moveFactor);
}
else {
TranslateAnimation anim = new TranslateAnimation(lastTranslate, moveFactor, 0.0f, 0.0f);
anim.setDuration(0);
anim.setFillAfter(true);
frame.startAnimation(anim);
lastTranslate = moveFactor;
}
}
};
drawerLayout.setDrawerListener(drawerListener);
drawerLayout.setScrimColor(getResources().getColor(android.R.color.transparent));
drawerLayout.setDrawerShadow(R.drawable.vertical_menu_line_shadow_effect, GravityCompat.START);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_post, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == R.id.action_post){
startActivity(new Intent(MainActivity.this, Post.class));
}
return drawerListener.onOptionsItemSelected(item);
}
private class SlideMenuClickListener implements
ListView.OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// display view for selected nav drawer item
displayView(position);
}
}
private void displayView(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
Intent intent;
switch (position) {
case 0:
fragment = new Profile_Fragment();
break;
case 1:
fragment = new TrendingFragment();
break;
case 2:
fragment = new Notification_Fragment();
break;
case 3:
fragment = new Follow_Updates();
break;
case 4:
fragment = new Favourites_Fragments();
break;
case 5:
fragment = new Settings_Fragment();
break;
case 6:
userLocalStore.clearUserData();
userLocalStore.setUserLoggedIn(false);
intent = new Intent(MainActivity.this, WelcomeActivity.class);
startActivity(intent);
break;
default:
break;
}
// update selected item and title, then close the drawer
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.mainContent, fragment).commit();
// update selected item and title, then close the drawer
drawerList.setItemChecked(position, true);
drawerList.setSelection(position);
drawerLayout.closeDrawer(drawerList);
} else {
Log.e("HomeActivity", "Error in creating fragment");
}
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
drawerListener.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerListener.onConfigurationChanged(newConfig);
}
private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
longitude = location.getLongitude();
latitude = location.getLatitude();
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
};
@Override
protected void onStart() {
super.onStart();
if(authenticate()) {
}
}
private boolean authenticate() {
if (userLocalStore.getLoggedInUser() == null) {
Intent intent = new Intent(this, WelcomeActivity.class);
startActivity(intent);
return false;
}
return true;
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
private void showErrorMessage() {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(MainActivity.this);
dialogBuilder.setMessage("Sorry! Something went wrong");
dialogBuilder.setPositiveButton("Ok", null);
dialogBuilder.show();
}
class MyAdapter extends BaseAdapter {
private Context context;
int[] menuIcons = { R.drawable.profile_icon_original, R.drawable.trending_original, R.drawable.notifications_icon_original, R.drawable.follow_icon_original ,R.drawable.favourites_icon_original,
R.drawable.settings_icon_original, R.drawable.logout_icon_original
};
public MyAdapter(Context context) {
this.context = context;
}
@Override
public int getCount() {
return menuIcons.length;
}
@Override
public Object getItem(int position) {
return menuIcons[position];
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row;
if(convertView==null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.custom_row, parent, false);
}
else {
row = convertView;
}
ImageView imageView = (ImageView) row.findViewById(R.id.imageView2);
imageView.setImageResource(menuIcons[position]);
return row;
}
}
public static boolean isLocationEnabled(Context context) {
int locationMode = 0;
String locationProviders;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
try {
locationMode = Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.LOCATION_MODE);
} catch (Settings.SettingNotFoundException e) {
e.printStackTrace();
}
return locationMode != Settings.Secure.LOCATION_MODE_OFF;
}else{
locationProviders = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
return !TextUtils.isEmpty(locationProviders);
}
}
public static void displayPromptForEnablingGPS(final Activity activity) {
final AlertDialog.Builder builder = new AlertDialog.Builder(activity);
final String action = Settings.ACTION_LOCATION_SOURCE_SETTINGS;
final String message = "Enable either GPS or any other location"
+ " service to find current location. Click OK to go to"
+ " location services settings to let you do so.";
builder.setMessage(message)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface d, int id) {
activity.startActivity(new Intent(action));
d.dismiss();
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface d, int id) {
d.cancel();
}
});
builder.create().show();
}
private void setProgressDialog(Context context) {
progressDialog = new ProgressDialog(context);
progressDialog.setCancelable(false);
progressDialog.setTitle("Processing...");
progressDialog.setMessage("Please wait...");
}
class StoreUserLocationAsyncTask extends AsyncTask<Void, Void, Void> {
User user;
@Override
protected Void doInBackground(Void... params) {
user = userLocalStore.getLoggedInUser();
postDataParams.put("userID", Integer.toString(user.userID));
postDataParams.put("longitude", String.valueOf(longitude));
postDataParams.put("latitude", String.valueOf(latitude));
performPostCall(SERVER_ADDRESS, postDataParams);
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
}
}
public String performPostCall(String requestURL, HashMap<String, String> postDataParams) {
URL url;
String response = "";
try {
url = new URL(requestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
int responseCode=conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line=br.readLine()) != null) {
response+=line;
}
}
else {
response="";
throw new HttpException(responseCode+"");
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
private String getPostDataString(Map<String, String> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for(Map.Entry<String, String> entry : params.entrySet()){
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return result.toString();
}
// @Override
// public void onBackPressed() {
// if (getFragmentManager().getBackStackEntryCount() == 0) {
/// this.finish();
/// super.onBackPressed();
/// } else {
// getFragmentManager().popBackStack();
// }
// }
}