Layout attributes in XML code those are ignored when using addView method

166 Views Asked by At

I'm korean, The image under is used korean language. Well.. This fact isn't important. I tried to add the custom view, In Linear layout, And It's be in linear layout successfully. But It's not on center horizontal. I did surely set the gravity of linearlayout center horizontal. But It isn't work. I guess cause of problem is layout params. Custom view class haven't problem, And not appeared any error on debugging. How do I do??

Activity in XML code:

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

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

There are 2 best solutions below

0
Sabbir Ahmed On BEST ANSWER

i think your subview layout_width="match_parent" please try this code

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

selectBody.addView(c0001); 
0
venu46 On

Try to set the gravity for custom views like this

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