以编程方式居中按钮

时间:2015-02-04 23:28:34

标签: android android-layout android-activity

我正在尝试以编程方式创建一个居中的按钮,按下时会打印一个单词。 我已经使用了Gravity,但是我遇到了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开发,并没有真正体验过这个。

谢谢!

1 个答案:

答案 0 :(得分: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
        }
    }
);