Android通过重新绘制相同的元素而没有任何失效来搞乱我的观点

时间:2016-03-29 00:13:22

标签: android android-layout android-studio

由于某些问题,我的应用中的所有活动都被重新绘制,看起来类似于下图。对我来说,一个hacky解决方法是将ImageView添加为最低层,与父级具有相同的高度和宽度,并将其用作背景,这似乎可以阻止此问题的发生。我在这里附加了一个活动的代码,但请注意,无论扩展BaseActivity类的活动如何,这都发生在所有活动中。

BaseActivityClass如下:

public class BaseActivity extends AppCompatActivity implements
    GoogleApiClient.OnConnectionFailedListener {

protected GoogleApiClient mGoogleApiClient;
protected Firebase.AuthStateListener mAuthListener;
protected Firebase mFirebaseRef;
protected FirebaseWrapper mFirebaseWrapper;
protected String mProvider;
protected String mEmail;
protected GSharedPreferences mSharedPref;

protected Location mCurrentLocation = null;


// Permission related variables
protected static final int FINE_LOCATION = 100;
protected View mLayout;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mSharedPref = GSharedPreferences.getInstance();

    // Allow google logins
    GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestEmail()
            .build();
    // Create new Client API
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
            .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
            .addApi(LocationServices.API)
            .build();
    mFirebaseWrapper = FirebaseWrapper.getInstance(mGoogleApiClient);
    mGoogleApiClient.connect();

    if (!((this instanceof LoginActivity) || (this instanceof CreateAccountActivity))) {
        mFirebaseRef = new Firebase(Constants.FIREBASE_URL);
        mAuthListener = new Firebase.AuthStateListener() {
            @Override
            public void onAuthStateChanged(AuthData authData) {
                if (authData == null) {
                    kickUserOut();
                }
            }
        };
        mFirebaseRef.addAuthStateListener(mAuthListener);
    }

    // Get the provider and email if set. A null value means the user is not yet authenticated.
    mEmail = mSharedPref.getPreference(Constants.ID_SHAREDPREF_EMAIL);
    mProvider = mSharedPref.getPreference(Constants.ID_SHAREDPREF_PROVIDER);

    requestAllPermissions();
}

@Override
protected void onStop() {
    super.onStop();
}

@Override
protected void onStart() {
    super.onStart();
}

@Override
public void onDestroy() {
    super.onDestroy();
    // The Auth listener is created only when the user is not a part of the login or
    // create account activity, do the cleanup only in such cases.
    if (!((this instanceof LoginActivity) || (this instanceof CreateAccountActivity))) {
        mFirebaseRef.removeAuthStateListener(mAuthListener);
    }
}

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
}

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

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();

    if (id == android.R.id.home) {
        super.onBackPressed();
        return true;
    }
    if (id == R.id.action_logout) {
        logout();
        return true;
    }
    return super.onOptionsItemSelected(item);
}



@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}


@Override
protected void onResume() {
    super.onResume();
    mSharedPref.writePreference(Constants.CAN_SHOW_NOTIFICATION, Constants.NO);
   // mSharedPref.writePreference(Constants.ID_SHAREDPREF_CANGOOFFLINE, Constants.NO);
}

@Override
protected void onPause() {
    super.onPause();
    mSharedPref.writePreference(Constants.CAN_SHOW_NOTIFICATION, Constants.YES);
}

/**
 * This is called from the child activities that are not associated
 * with login or account creation flows.
 */
protected void logout() {
    Toast.makeText(this, "Attemping to logout.", Toast.LENGTH_LONG);
    // mProvider is set only after the user logs in successfully.
    if (mProvider != null) {
        mFirebaseRef.unauth();
        if (mProvider.equals(Constants.GOOGLE_AUTH_PROVIDER)) {
            Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
                    new ResultCallback<Status>() {
                        @Override
                        public void onResult(Status status) {
                            // We do not intend to do anything after logout.
                            // Ignore.
                        }
                    });
        }
    }
}

private void kickUserOut() {
    mSharedPref.clear();
    // Shared prefs store data about email, clear that and kick users out by moving them
    // to login screen.
    Intent intent = new Intent(BaseActivity.this, LoginActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    startActivity(intent);
    finish();
}

protected void showToast(String aText) {
    Toast.makeText(this, aText, Toast.LENGTH_SHORT).show();
}

public void requestAllPermissions() {
    mLayout = findViewById(R.id.main_layout);

    if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED) {
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.ACCESS_FINE_LOCATION)) {

            Log.i("MainActivity",
                    "Displaying location permission rationale to provide additional context.");

            Snackbar.make(mLayout, R.string.permission_location_rationale,
                    Snackbar.LENGTH_INDEFINITE)
                    .setAction(R.string.ok, new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            ActivityCompat.requestPermissions(BaseActivity.this,
                                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                                    FINE_LOCATION);
                        }
                    })
                    .show();
        } else {

            // Location permission has not been granted yet. Request it directly.
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    FINE_LOCATION);
        }
    }
}

protected LatLng getCurrentLocation()
{
    Location currentLocation = LocationServices.FusedLocationApi.getLastLocation(
            mGoogleApiClient);
    float lat = (float) (currentLocation == null ? -190.00: currentLocation.getLatitude());
    float lon = (float) (currentLocation == null ? -190.00: currentLocation.getLongitude());
    return new LatLng(lat, lon);
}
}

我有一个PreferenceActivity,它有相同的问题,看起来像附加的图像。

public class SettingsActivity extends PreferenceActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getFragmentManager().beginTransaction().replace(android.R.id.content, new MyPreferenceFragment()).commit();
    }

    public static class MyPreferenceFragment extends PreferenceFragment
    {
        @Override
        public void onCreate(final Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            addPreferencesFromResource(R.layout.activity_settings);
        }
    }

}

执行以下操作(将ImageView添加为第一个子项,将整个视图作为背景包含在内)解决了这个问题。

<?xml version="1.0" encoding="utf-8"?>
<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:id="@+id/main_layout">

    <ImageView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:scaleType="centerCrop"
        android:src="@drawable/bg2"
        />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
        <ListView
            android:id="@+id/list_view_actions_list"
            android:drawSelectorOnTop="true"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:dividerHeight="2dp"
            android:scrollbars="none" />

    </LinearLayout>
</RelativeLayout>

我很感激任何提示/线索,我可能做错了什么以及如何解决这个问题。如果我将ImageView作为背景,那么一切正常,但我不想总是坚持一种修复问题的黑客方法。此外,ImageView修复程序仅在它是RelativeLayout时才有效。 (如果你有兴趣看到我的代码在github上托管。

Messed up UI

我的代码托管在https://github.com/neerajcse/dstudio/

0 个答案:

没有答案