본문 바로가기

안드로이드

안드로이드 동적 textview 생성

import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

private static final float FONT_SIZE = 10;
private LinearLayout container;

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

//부모 뷰
container = (LinearLayout) findViewById(R.id.layout);

textview("1");
textview("2");
textview("3");

}
public void textview(String a){
//TextView 생성
TextView view1 = new TextView(this);
view1.setText(a);
view1.setTextSize(FONT_SIZE);
view1.setTextColor(Color.BLACK);

//layout_width, layout_height, gravity 설정
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
lp.gravity = Gravity.CENTER;
view1.setLayoutParams(lp);

//부모 뷰에 추가
container.addView(view1);
}
}