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

时间:2018-02-13 10:46:53

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

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

XML代码中的活动:

<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>

AddView方法:

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);
}

2 个答案:

答案 0 :(得分:1)

尝试像这样设置自定义视图的重力

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.gravity = Gravity.CENTER;
c0001.setLayoutParams(params); //your custom ThemeView

答案 1 :(得分:1)

我认为你的子视图layout_width =&#34; match_parent&#34;请尝试此代码

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

selectBody.addView(c0001);