developer tip

RelativeLayout에 프로그래밍 방식으로 뷰를 추가하는 방법은 무엇입니까?

optionbox 2020. 12. 11. 08:04
반응형

RelativeLayout에 프로그래밍 방식으로 뷰를 추가하는 방법은 무엇입니까?


RelativeLayout주어진 위치에 프로그래밍 방식으로 자식 뷰를 추가하는 아주 간단한 예를 들어 주 시겠습니까?

예를 들어 다음 XML을 반영하려면 :

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:layout_marginLeft="107dp"
    android:layout_marginTop="103dp"
    android:text="Large Text"
    android:textAppearance="?android:attr/textAppearanceLarge" />

적절한 RelativeLayout.LayoutParams인스턴스 를 만드는 방법을 이해하지 못합니다 .


시작하기위한 예는 다음과 같습니다. 나머지는 해당하는대로 입력하세요.

TextView tv = new TextView(mContext);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
    ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE);
params.leftMargin = 107
...
mRelativeLayout.addView(tv, params);

RelativeLayout.LayoutParams 및 생성자에 대한 문서는 여기에 있습니다.


첫째, RelativeLayout에 id를 주어야합니다 relativeLayout1.

RelativeLayout mainLayout = (RelativeLayout) findViewById(R.id.relativeLayout1);
TextView mTextView = new TextView(context);
mTextView.setText("Dynamic TextView");
mTextView.setId(111);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE);
params.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);
mainLayout.addView(mTextView, params);

참고 URL : https://stackoverflow.com/questions/10418929/how-to-add-a-view-programmatically-to-relativelayout

반응형