2015-07-13 5 views
0

Это, наверное, просто глупая ошибка, но я не могу ее исправить. У меня есть знак Google+, который отображается, когда пользователь не вошел в систему. У меня также есть кнопка выхода, которая GONE, когда пользователь зарегистрирован. Все работает, за исключением того, что когда я возвращаюсь к активности (onResume) Я вижу красную кнопку Google+ около секунды, а затем скрывается, и появляется кнопка выхода. Как я могу удалить эту секунду, в течение которой я все еще могу видеть кнопку Google+?Почему моя кнопка показана и чем быстро скрыта?

Это мой макет: enter image description here

код XML:

<ImageView 
    android:layout_width="100dp" 
    android:layout_height="100dp" 
    android:id="@+id/startGameView" 
    android:src="@drawable/play" 
    android:layout_alignParentBottom="true" 
    android:layout_centerHorizontal="true"/> 

<LinearLayout 
    android:orientation="horizontal" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_above="@+id/startGameView" 
    android:layout_centerHorizontal="true" 
    android:layout_marginBottom="46dp"> 
    <!-- show achievements --> 
    <Button 
     android:id="@+id/show_achievements" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="Achievements"/> 

    <!-- show leaderboards --> 
    <Button 
     android:id="@+id/show_leaderboard" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="Leaderboard"/> 
</LinearLayout> 

Код в деятельности:

public class StartActivity extends BaseGameActivity implements View.OnClickListener{ 
private ImageView mPlay; 

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

    mPlay = (ImageView)findViewById(R.id.startGameView); 
    mPlay.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      //play animations 
      YoYo.with(Techniques.Pulse) 
        .duration(200) 
        .playOn(findViewById(R.id.startGameView)); 
      Intent intent = new Intent(StartActivity.this, MainActivity.class); 
      startActivity(intent); 
     } 
    }); 
    findViewById(R.id.sign_in_button).setOnClickListener(this); 
    findViewById(R.id.sign_out_button).setOnClickListener(this); 
    findViewById(R.id.show_achievements).setOnClickListener(this); 
    findViewById(R.id.show_leaderboard).setOnClickListener(this); 
    //mSignOutButton = (Button)findViewById(R.id.sign_out_button); 
} 

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.menu_start, menu); 
    return true; 
} 

@Override 
public boolean onOptionsItemSelected(MenuItem item) { 
    // Handle action bar item clicks here. The action bar will 
    // automatically handle clicks on the Home/Up button, so long 
    // as you specify a parent activity in AndroidManifest.xml. 
    int id = item.getItemId(); 

    //noinspection SimplifiableIfStatement 
    if (id == R.id.action_settings) { 
     return true; 
    } 

    return super.onOptionsItemSelected(item); 
} 

@Override 
public void onSignInFailed() { 
    findViewById(R.id.sign_in_button).setVisibility(View.VISIBLE); 
    findViewById(R.id.sign_out_button).setVisibility(View.GONE); 
} 

@Override 
public void onSignInSucceeded() { 
    findViewById(R.id.sign_in_button).setVisibility(View.GONE); 
    findViewById(R.id.sign_out_button).setVisibility(View.VISIBLE); 
} 

@Override 
public void onClick(View view) { 
    if (view.getId() == R.id.sign_in_button) { 
     beginUserInitiatedSignIn(); 
    }else if (view.getId() == R.id.sign_out_button) { 
     signOut(); 
     findViewById(R.id.sign_in_button).setVisibility(View.VISIBLE); 
     findViewById(R.id.sign_out_button).setVisibility(View.GONE); 
    }else if (view.getId() == R.id.show_achievements){ 
     Toast.makeText(StartActivity.this,"achivements",Toast.LENGTH_SHORT).show(); 
     startActivityForResult(Games.Achievements.getAchievementsIntent(getApiClient()), 1); 
    }else if(view.getId() == R.id.show_leaderboard){ 
     Toast.makeText(StartActivity.this,"leaderboard",Toast.LENGTH_SHORT).show(); 
     startActivityForResult(Games.Leaderboards.getLeaderboardIntent(
       getApiClient(), getString(R.string.number_of_solved_math_problems_leaderboard)), 2); 
    } 
} 

BaseActivity код:

public abstract class BaseGameActivity extends FragmentActivity implements 
    GameHelper.GameHelperListener { 

// The game helper object. This class is mainly a wrapper around this object. 
protected GameHelper mHelper; 

// We expose these constants here because we don't want users of this class 
// to have to know about GameHelper at all. 
public static final int CLIENT_GAMES = GameHelper.CLIENT_GAMES; 
public static final int CLIENT_APPSTATE = GameHelper.CLIENT_APPSTATE; 
public static final int CLIENT_PLUS = GameHelper.CLIENT_PLUS; 
public static final int CLIENT_ALL = GameHelper.CLIENT_ALL; 

// Requested clients. By default, that's just the games client. 
protected int mRequestedClients = CLIENT_GAMES; 

private final static String TAG = "BaseGameActivity"; 
protected boolean mDebugLog = false; 

/** Constructs a BaseGameActivity with default client (GamesClient). */ 
protected BaseGameActivity() { 
    super(); 
} 

/** 
* Constructs a BaseGameActivity with the requested clients. 
* @param requestedClients The requested clients (a combination of CLIENT_GAMES, 
*   CLIENT_PLUS and CLIENT_APPSTATE). 
*/ 
protected BaseGameActivity(int requestedClients) { 
    super(); 
    setRequestedClients(requestedClients); 
} 

/** 
* Sets the requested clients. The preferred way to set the requested clients is 
* via the constructor, but this method is available if for some reason your code 
* cannot do this in the constructor. This must be called before onCreate or getGameHelper() 
* in order to have any effect. If called after onCreate()/getGameHelper(), this method 
* is a no-op. 
* 
* @param requestedClients A combination of the flags CLIENT_GAMES, CLIENT_PLUS 
*   and CLIENT_APPSTATE, or CLIENT_ALL to request all available clients. 
*/ 
protected void setRequestedClients(int requestedClients) { 
    mRequestedClients = requestedClients; 
} 

public GameHelper getGameHelper() { 
    if (mHelper == null) { 
     mHelper = new GameHelper(this, mRequestedClients); 
     mHelper.enableDebugLog(mDebugLog); 
    } 
    return mHelper; 
} 

@Override 
protected void onCreate(Bundle b) { 
    super.onCreate(b); 
    if (mHelper == null) { 
     getGameHelper(); 
    } 
    mHelper.setup(this); 
} 

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

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

@Override 
protected void onActivityResult(int request, int response, Intent data) { 
    super.onActivityResult(request, response, data); 
    mHelper.onActivityResult(request, response, data); 
} 

protected GoogleApiClient getApiClient() { 
    return mHelper.getApiClient(); 
} 

protected boolean isSignedIn() { 
    return mHelper.isSignedIn(); 
} 

protected void beginUserInitiatedSignIn() { 
    mHelper.beginUserInitiatedSignIn(); 
} 

protected void signOut() { 
    mHelper.signOut(); 
} 

protected void showAlert(String message) { 
    mHelper.makeSimpleDialog(message).show(); 
} 

protected void showAlert(String title, String message) { 
    mHelper.makeSimpleDialog(title, message).show(); 
} 

protected void enableDebugLog(boolean enabled) { 
    mDebugLog = true; 
    if (mHelper != null) { 
     mHelper.enableDebugLog(enabled); 
    } 
} 

@Deprecated 
protected void enableDebugLog(boolean enabled, String tag) { 
    Log.w(TAG, "BaseGameActivity.enabledDebugLog(bool,String) is " + 
      "deprecated. Use enableDebugLog(boolean)"); 
    enableDebugLog(enabled); 
} 

protected String getInvitationId() { 
    return mHelper.getInvitationId(); 
} 

protected void reconnectClient() { 
    mHelper.reconnectClient(); 
} 

protected boolean hasSignInError() { 
    return mHelper.hasSignInError(); 
} 

protected GameHelper.SignInFailureReason getSignInError() { 
    return mHelper.getSignInError(); 
} 
+1

могли бы вы добавить свой код BaseGameActivity? – pjanecze

+0

Я добавил код для BaseActivity. Если вы ищете переопределение метода onResume, эта деятельность не делает этого. Я уже проверил:/ –

+1

Держите кнопки по умолчанию в макете. В onResume вы просто переключаете видимость. Опыт улучшится таким образом. –

ответ

1

Если вы недавно клонировали (или обновили) образцы, вы заметите, что GameHelper и BaseGameActivity больше не используются. Информационное видео об этом изменении: Game On! - The death of BaseGameActivity. Если вы просто реализуете интерфейсы для получения обратных вызовов для состояния: GoogleApiClient.ConnectionCallbacks и GoogleApiClient.OnConnectionFailedListener ваша проблема должна исчезнуть.

Более конкретные сведения о том, как использовать эти интерфейсы в https://developers.google.com/games/services/training/signin

+0

Благодарим вас за ответ. Я не знал, что эти два класса устарели. Я попробую этот подход :) –

1

Как я вижу в GameHelper class, он отключается от googleApiClient по onStop() и подключается к onStart(). Это вызывает мигание кнопок.

Если вы не хотите менять GameHelper, сделайте некоторое улучшение пользовательского интерфейса, чтобы сделать его менее раздражающим.

+0

Спасибо за ваше предложение. Тем не менее, я уже применил то, что предложил @sushant, и он отлично работает. –

+0

О, я ошибся, его предложение не работает:/ –

Смежные вопросы