Программное добавление элементов в Android (Java)

В этой статье разбираемся как осуществить программное добавление элементов в Android. В следующем фрагменте кода показано объявление элементов, настройка их параметров и отображение их в LinearLayout.

Добавляем элементы в активити из кода

Привожу пример программного добавления элементов:

package razilov.ru;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LinearLayout linearLayout = new LinearLayout(this);
        linearLayout.setOrientation(LinearLayout.VERTICAL);
        ViewGroup.LayoutParams linLayoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        setContentView(linearLayout, linLayoutParams);
        ViewGroup.LayoutParams lpView = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        TextView tv = new TextView(this);
        tv.setText("TextView");
        tv.setLayoutParams(lpView);
        linearLayout.addView(tv);
        Button btn = new Button(this);
        btn.setText("Button");
        linearLayout.addView(btn, lpView);
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        layoutParams.leftMargin = 50;
        Button btn1 = new Button(this);
        btn1.setText("Btn1");
        linearLayout.addView(btn1, layoutParams);
        LinearLayout.LayoutParams layoutParams1 = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        layoutParams1.gravity = Gravity.RIGHT;
        Button btn2 = new Button(this);
        btn2.setText("btn2");
        linearLayout.addView(btn2, layoutParams1);
    }
}

Функция addView добавляет элемент в контрол.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *