Вы также можете сделать это из своего обработчика (в классе реализации).
После раздувания макета xml вы реагируете на какие-то взаимодействия с пользователем.
В обработчике у тебя
- либо создайте новый вид из
поцарапать, и указать его
layoutparams
- или надуйте один, используя xml
Получив новый вид, вы добавляете его в текущий (this
) вид, и из-за его параметров макета вам будут необходим размер, форма, цвет и т. Д.
Обновление:
Если вы хотите добавить к своей деятельности более сложные представления, лучше написать их в формате xml и надуть их:
sample_component.xml: // внутри res / layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:padding="0px">
<TextView android:id="@+id/servicename_status" android:paddingLeft="15px"
android:paddingRight="5px"
android:textStyle="bold" android:focusable="false" android:textSize="14px"
android:layout_marginLeft="10px" android:layout_marginRight="3px"
android:layout_width="fill_parent" android:layout_height="wrap_content" />
<TextView android:id="@+id/lastcheck" android:focusable="false"
android:textSize="14px" android:layout_width="fill_parent"
android:layout_marginLeft="10px" android:layout_marginRight="3px"
android:layout_height="wrap_content" android:layout_below="@id/servicename_status" />
<TextView android:id="@+id/duration" android:focusable="false"
android:textSize="14px" android:layout_width="fill_parent"
android:layout_marginLeft="10px" android:layout_marginRight="3px"
android:layout_height="wrap_content" android:layout_below="@id/lastcheck" />
<TextView android:id="@+id/attempt" android:focusable="false"
android:textSize="14px" android:layout_width="fill_parent"
android:layout_marginLeft="10px" android:layout_marginRight="3px"
android:layout_height="wrap_content" android:layout_below="@id/duration" />
<TextView android:id="@+id/statusinfo" android:focusable="false"
android:textSize="14px" android:layout_width="fill_parent"
android:layout_marginLeft="10px" android:layout_marginRight="3px"
android:layout_height="wrap_content" android:layout_below="@id/attempt" />
<CheckBox android:id="@+id/alert" android:focusable="false"
android:layout_alignParentRight="true" android:freezesText="false"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_marginTop="5px" />
</RelativeLayout>
В вашем классе активности Leonidas
есть обработчики, которые должны реагировать на различные действия пользователя, добавляя / удаляя элементы в / из представления.
Ниже приведен пример обработчика события щелчка, который использует LayoutInflater
, чтобы добавить представление sample_component.xml
к вашей активности:
public final class MyClickListener implements View.OnClickListener
{
private LayoutInflater inflater;
public MyClickListener()
{
inflater = LayoutInflater.from(Leonidas .this);
}
@Override
public void onClick(View v)
{
// TODO: change RelativeLayout here to whatever layout
// you'd like to add the new components to
final RelativeLayout canvas = (RelativeLayout)Leonidas.this.findViewById(R.id.my_canvas);
final View childView = inflater.inflate(R.layout.sample_component, canvas, false);
// TODO: Look up the 5 different signatures of the addView method,
// and pick that best fits your needs
canvas.addView(childView);
// check which button was pressed
switch (view.getId())
{
case R.id.btn_prev:
//handler for the prev button
break;
case R.id.btn_next:
//handler for the next button
break;
default:
break;
}
}
}
Обратите внимание, что MyClickListener реализован как встроенный класс в вашей активности Leonidas, поэтому для параметра context
он используется: this.Leonidas
.
Обновление
R.id.my_canvas будет идентификатором представления, к которому вы хотите добавить компоненты. он находится в вашем main.xml (или любом другом xml, который вы используете для представления Leonidas).
Если вы поместите класс MyClickListener в свой класс Leonidas.java (объявите как встроенный класс), он его распознает.