Существует множество способов сделать это, это просто вопрос о том, как вы справляетесь с этим. Предпочтительнее сохранить создание своего макета в XML, поскольку он сохраняет логику создания своего вида отдельно от вашей логики приложения, что приводит к созданию более чистого кода. Кроме того, как только вы привыкнете к XML, это самый простой, на мой взгляд. Я покажу несколько способов справиться с вашей проблемой ...
border.xml
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#ffffffff"/>
<stroke android:width="3dp"
android:color="#ff000000"
/>
<padding android:left="1dp"
android:top="1dp"
android:right="1dp"
android:bottom="1dp"
/>
<corners android:bottomRightRadius="7dp"
android:bottomLeftRadius="7dp"
android:topLeftRadius="7dp"
android:topRightRadius="7dp"/>
</shape>
row_view.xml - не идеально, но легко модифицируются.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/border"
android:layout_margin="2dp" >
<TextView
android:id="@+id/text_number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="16dp"
android:paddingTop="16dp"
android:paddingBottom="16dp"
android:text="1"
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_alignParentLeft="true" />
<TextView
android:id="@+id/text_record"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Record: ###"
android:textAppearance="?android:attr/textAppearanceSmall"
android:layout_centerInParent="true" />
<CheckBox
android:id="@+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:paddingRight="8dp"
android:checked="true"/>
</RelativeLayout>
Отсюда, вы могли бы пойти об этом нескольких различных способах - первом, будет использовать включаемое заявление в другом XML и просто использовать этот макет, затем траверс всех представлений для того, чтобы установить вверх ваш взгляд. Это своего рода грязные, поэтому я не предпочитаю его, но XML будет выглядеть следующим образом:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/main_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<include layout="@layout/row_view"/>
<include layout="@layout/row_view"/>
<include layout="@layout/row_view"/>
</LinearLayout>
Тогда можно просто надуть этот XML в своей деятельности, и траверса ваших взглядов. Другой вариант - раздуть и добавить. Вот краткий пример каждого, просто измените поле current_type, чтобы увидеть результат каждого ...:
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class MainActivity extends Activity {
private static final int NUMBER_OF_ROWS = 3;
private static final int XML_TRAVERSAL = 1;
private static final int ADD_VIEW = 2;
private static int current_type = ADD_VIEW;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(current_type == XML_TRAVERSAL){
setUpUsingTraversal();
} else {
setUpByInflating();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private void setUpUsingTraversal(){
setContentView(R.layout.container_view);
LinearLayout main_view = (LinearLayout) findViewById(R.id.main_view);
int count = main_view.getChildCount();
for(int i = 0; i < count ; i++){
RelativeLayout layout = (RelativeLayout) main_view.getChildAt(i);
setTextOnViews(layout, i);
}
}
private void setUpByInflating() {
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
layout.setLayoutParams(new ViewGroup.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
for(int x = 0; x < NUMBER_OF_ROWS ; x++){
RelativeLayout row = (RelativeLayout) getLayoutInflater().inflate(R.layout.row_view, layout, false);
setTextOnViews(row,x);
layout.addView(row);
}
setContentView(layout);
}
private void setTextOnViews(ViewGroup view, int position){
((TextView)view.getChildAt(0)).setText(Integer.toString(position));
((TextView)view.getChildAt(1)).setText("Record: " + Integer.toString(position));
}
}
Наконец, другой маршрут можно взять (который вы упомянули слишком многословным) было бы сделать один xml-файл, который уже содержит правильные значения и просто раздувается и выполняется.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/main_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="2dp"
android:background="@drawable/border" >
<TextView
android:id="@+id/text_number1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:paddingBottom="16dp"
android:paddingLeft="16dp"
android:paddingTop="16dp"
android:text="1"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="@+id/text_record1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Record: ###"
android:textAppearance="?android:attr/textAppearanceSmall" />
<CheckBox
android:id="@+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:checked="true"
android:paddingRight="8dp" />
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="2dp"
android:background="@drawable/border" >
<TextView
android:id="@+id/text_number2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:paddingBottom="16dp"
android:paddingLeft="16dp"
android:paddingTop="16dp"
android:text="2"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="@+id/text_record2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Record: ###"
android:textAppearance="?android:attr/textAppearanceSmall" />
<CheckBox
android:id="@+id/checkBox2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:checked="true"
android:paddingRight="8dp" />
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="2dp"
android:background="@drawable/border" >
<TextView
android:id="@+id/text_number3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:paddingBottom="16dp"
android:paddingLeft="16dp"
android:paddingTop="16dp"
android:text="3"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="@+id/text_record3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Record: ###"
android:textAppearance="?android:attr/textAppearanceSmall" />
<CheckBox
android:id="@+id/checkBox3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:checked="true"
android:paddingRight="8dp" />
</RelativeLayout>
</LinearLayout>
EDIT:
Кроме того, если вы хотите, чтобы достичь этого с LinearLayout, а не RelativeLayout XML-бы выглядеть следующим образом:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:background="@drawable/border" >
<TextView
android:id="@+id/text_number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="16dp"
android:text="1"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="@+id/text_record"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:text="Record: ###"
android:textAppearance="?android:attr/textAppearanceSmall" />
<CheckBox
android:id="@+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:paddingRight="8dp" />
</LinearLayout>
Так что, если вы делаете это программно , вы должны установить следующие параметры макета:
LinearLayout.LayoutParams forNumberAndCheckBox = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
LinearLayout.LayoutParams forRecord = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, 1);
Вы заметили, что все ваши весы соответствуют номиналу AMS1? Имена информационных переменных всегда являются хорошей идеей. –
О брат, это было глупо. В любом случае, спасибо! – Matt
Мы все были там, сделали это, да? :) –