728x90

LinearLayout 동적 생성 코드이다.


import android.graphics.Color;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.Gravity;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

public class TestActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        LinearLayout myLinearLayout = new LinearLayout(this);
        myLinearLayout.setOrientation(LinearLayout.VERTICAL);

        LinearLayout.LayoutParams mParams = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);

        final EditText editText = new EditText(this);
        editText.setHint("여기에 입력하세요");
        mParams.setMargins(0,50,0,10);
        editText.setLayoutParams(mParams);
        myLinearLayout.addView(editText);

        DisplayMetrics dm = getResources().getDisplayMetrics();
        int size = Math.round(20 * dm.density);

        Button btn = new Button(this);
        btn.setText("버튼");
        btn.setBackgroundColor(Color.YELLOW);
        mParams.topMargin = size;
        btn.setLayoutParams(mParams);
        myLinearLayout.addView(btn);

        LinearLayout.LayoutParams tv_params = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);

        final TextView textView = new TextView(this);
        textView.setText("텍스트뷰입니다.");
        textView.setTextColor(Color.MAGENTA);
        textView.setTextSize(TypedValue.COMPLEX_UNIT_SP,18);
        tv_params.gravity = Gravity.CENTER;
        tv_params.setMargins(0,50,0,0);
        textView.setLayoutParams(tv_params);
        myLinearLayout.addView(textView);

        setContentView(myLinearLayout);

        btn.setOnClickListener(view -> textView.setText(editText.getText().toString()));
    }

}


결과 화면


 


코드파일 및 결과 이미지

dynamicLayout.zip


728x90

'안드로이드 > Layout' 카테고리의 다른 글

하단 TabLayout + ViewPager Layout 예제  (0) 2020.11.01
LinearLayout 예제  (0) 2020.10.13
SMS authentication with OTP Layout Example  (0) 2020.09.14
EditText DatePicker  (0) 2020.08.18
Floating Action Button  (0) 2020.07.11
블로그 이미지

Link2Me

,