android - 以编程方式使按钮居中

标签 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开发,对这方面还不是很了解。

谢谢!

最佳答案

为了获得布局的高度和宽度,您需要等待 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
        }
    }
);

关于android - 以编程方式使按钮居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28333558/

相关文章:

android - 将 PhoneGap 插件的中间结果发送到 JavaScript 代码

java - 我需要帮助将图像存储在内部目录中,并且其路径已插入SQLite中

java - 如何将数组解析为数组 JSON

android - 处理大量图像资源的最佳方法?

android - ConstraintLayout 没有响应

android - 长按无法在 Android 的 Edittext 中选择文本?

android - 如何用不同的数据调用相同的 Activity (相同的布局)?

android - 使用MediaPlayer添加声音后,为什么我的Android应用程序崩溃

java - 如何解决java.lang.RuntimeException : Unable to start activity?

android - 为android中的应用程序制作小部件