你有很多可能性来创建这种布局:
- 父
RelativeLayout,LinearLayout,顶部有 4 个点,底部显示您的视图,the attributes 为 toLeftOf、toRightOf 等 - 创建一个 onClickListener 方法来更改它们的状态并保存号码。
- 多个
LinearLayouts 和weight 属性填充整个空间,每个视图(四舍五入)填充空间(请参阅下面的示例以了解权重属性) - 或几个RelativeLayouts - 甚至是一个TableLayout。
- 或
LinearLayout 和GridView 下面使用ItemClickListener 方法..
根据您问题下方的cmets,有很多可能性。我用 Linear 和 RelativeLayout 选择其中之一。可能是这样的:
<!-- named activity_main.xml -->
<RelativeLayout
... >
<LinearLayout
android:id="@+id/contain"
... android:layout_width="250dip"
android:orientation="horizontal"
android:weightSum="4" >
<!-- weightSum to 4 = whatever the screen, display
my children views in 4 sections -->
<View
... android:layout_weight="1"
android:background="@drawable/green_dots" />
<!-- weight to 1 = this takes one section -->
<View
... android:layout_weight="1"
android:background="@drawable/green_dots" />
<!-- weight to 1 = this takes one section -->
<View
... android:layout_weight="1"
android:background="@drawable/green_dots" />
<View
... android:layout_weight="1"
android:background="@drawable/green_dots" />
</LinearLayout>
<RelativeLayout
android:layout_below="@id/contain" ... >
... Here display your buttons (or textviews) with
custom drawable background for each one
</RelativeLayout>
在您的Activity 类中,它实现OnClickListener 如下:
public class MyActivity extends Activity implements OnClickListener { }
然后在这个 Activity 中的方法中:
// init your buttons var
Button one, two, three, four, five ...;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// set the layout above
setContentView(R.layout.activity_main);
// init your buttons
one = (Button) findViewById(R.id.button1);
two = (Button) findViewById(R.id.button2);
three = (Button) findViewById(R.id.button3);
... etc.
// set them to your implementation
one.setOnClickListener(this);
two.setOnClickListener(this);
three.setOnClickListener(this);
... etc.
}
// call this function when one button is pressed
public void onClick(View view) {
// retrieves the id of clicked button
switch(view.getId()) {
case R.id.button1:
methodToSaveNumber(int);
break;
case R.id.button2:
methodToSaveNumber(int);
break;
case R.id.button3:
methodToSaveNumber(int);
break;
... etc.
}
}
然后在你的methodToSaveNumber 方法中:
// finally, your method to save the number of the password
public void methodToSaveNumber(int i) {
... do something.
... change the state of the buttons, the dots, whatever you want
}
为了向您展示它是如何工作的,可绘制的green_dots 可能是这样的:
<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<!-- radius -->
<corners
android:radius="20dp" />
<!-- border -->
<stroke
android:color="@android:color/green"
android:width="2dp" />
<!-- background (transparent) -->
<solid
android:color="#00000000" />
</shape>
您必须告知您layouts 及其工作原理、click event and its listener、drawables and their states(聚焦、按下、禁用……),最后,希望您能得到您想要的.
编码愉快!