android - XML 代码中的布局属性在使用 addView 方法时会被忽略

标签 android android-layout android-view android-gravity

我是韩国人,下面的图片使用的是韩语。嗯..这个事实并不重要。我尝试在线性布局中添加自定义 View ,并且它成功地处于线性布局中。但它不在水平中心。我确实将线性布局中心的重力设置为水平。但这是行不通的。我猜问题的原因是布局参数。自定义 View 类没有问题,调试时也没有出现任何错误。我该怎么办??

XML 代码中的 Activity :

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    tools:ignore="NestedScrolling">
    <LinearLayout
        android:id="@+id/select_body"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="30dp"
        android:gravity="center_horizontal"
        android:orientation="vertical">
        <!--Here is-->
    </LinearLayout>
</ScrollView>

添加 View 方法:

ThemeManager mTheme;

Button selectTopBoardButton;

LinearLayout selectBody;

ThemeView c0001;
ThemeView c0002;
ThemeView c0003;

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

    gestureDetectorCompat = new GestureDetectorCompat(this, new MainActivityGoer());

    NetworkDetector networkDetector = new NetworkDetector(this);
    if (!networkDetector.isConnected()) {
        Toast.makeText(SelectActivity.this, "네트워크에 접속할 수 없습니다.", Toast.LENGTH_SHORT).show();
    }

    selectTopBoardButton = (Button) findViewById(R.id.select_top_board_button);
    selectBody = (LinearLayout) findViewById(R.id.select_body);

    mTheme = new ThemeManager(this);
    c0001 = mTheme.getThemeView("c0001");
    c0002 = mTheme.getThemeView("c0002");
    c0003 = mTheme.getThemeView("c0003");

    selectTopBoardButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            String url = getResources().getString(R.string.main_request_btn06_url);
            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
        }
    });

    selectBody.addView(c0001);
}

最佳答案

我认为您的 subview layout_width="match_parent"请尝试此代码

c0001.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

selectBody.addView(c0001); 

关于android - XML 代码中的布局属性在使用 addView 方法时会被忽略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48764950/

相关文章:

android-layout - 安卓 : Attempting to switch between two Images and display them as the same size

android - Android 中的半透明状态栏

android - 如何更改按钮上 Compound Drawable 的颜色?

android - 如何在 RelativeLayout 中找到导致循环依赖的原因

java - android.widget.Toolbar 和 android.support.v7.widget.Toolbar 有什么区别?

java - 二进制 XML 文件行 #7 : Error inflating class android. support.v4.view.ViewPager

android - ArrayList 为空且出现错误

android - 应用 LayoutParams 隐藏 View

用于具有 2 个左连接的移动应用程序的 PHP 脚本

java - Proguard 只保留类名以及类中的所有成员和方法