2015-02-04 94 views
1

我試圖以編程方式創建一個居中按鈕,該按鈕在按下時會打印一個單詞。 我已經使用了重力對於這一點,但是我得到2個錯誤:以編程方式居中按鈕

eglSurfaceAttrib not implemented 
Failed to set EGL_SWAP_BEHAVIOR on surface 0xae0ee360, error=EGL_SUCCESS 

下面是我的代碼:

import android.support.v7.app.ActionBarActivity; 
import android.os.Bundle; 
import android.view.Gravity; 
import android.view.Menu; 
import android.view.MenuItem; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.Button; 
import android.widget.FrameLayout; 


public class MainActivity extends ActionBarActivity { 

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

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

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

    return super.onOptionsItemSelected(item); 
} 

///////////// 

@Override 
protected void onCreate(Bundle bundle) { 

    super.onCreate(bundle); 
    setContentView(R.layout.activity_main); 

    final ViewGroup vg1 = (ViewGroup) findViewById(android.R.id.content); 
    float w1 = vg1.getWidth(); 
    float h1 = vg1.getHeight(); 

    final Button b1 = new Button(this); 

    b1.setText(""); 

    float left = (w1 - vg1.getWidth())/2; 
    float top = (h1 - vg1.getHeight())/2; 

    FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams((int)w1/2, (int)h1/2); 
    layoutParams.setMargins((int)left, (int)top, (int)(left+w1/2), (int)(top+h1/2)); 
    layoutParams.gravity = Gravity.CENTER; 

    b1.setLayoutParams(layoutParams); 
    vg1.addView(b1, layoutParams); 

    b1.setOnClickListener(new View.OnClickListener(){ 
     @Override 
     public void onClick(View v) {     
       b1.setText("TestTest"); 
     } 
    }); 
} 

和XML:

<FrameLayout 
xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="match_parent" 
android:layout_height="match_parent"> 

請,幫我找到我的錯誤。 我剛開始學習android開發,並沒有真正體驗過這個。

謝謝!

+0

'浮W1 = vg1.getWidth();'和'浮H1 = vg1.getHeight();'可能是零。 – stkent

+0

是的,你是對的。但是,這可能會導致錯誤? –

+0

這是一個OpenGL錯誤,通常可以在模擬器上彈出。當涉及到佈局時,通常不需要擔心什麼。 – DeeV

回答

1

爲了獲得佈局的高度和寬度,您需要等待measure()傳遞(更多信息,請參閱https://developer.android.com/guide/topics/ui/how-android-draws.html)。 例如,你可以在你的佈局添加一個偵聽器:

gv1.getViewTreeObserver().addOnGlobalLayoutListener(
    new ViewTreeObserver.OnGlobalLayoutListener() { 
     public void onGlobalLayout() { 
      // execute your code here, after height and width have been calculated 
     } 
    } 
);