我有一个5线性布局,每个包含10个按钮,这就产生了一个5×10的按钮数组。我希望用户选择5个按钮,每个按钮包含一个特定的点值。在下一页中,我希望这5个按钮的点值之和出现在文本视图中。
以下是我迄今为止所尝试的,使用了我的代码的一个小示例。
xml文件上的:(这是一个2×3的示例)
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="@+id/button11"
android:layout_width="0dip"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="50" />
<Button
android:id="@+id/button12"
android:layout_width="0dip"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="50" />
<Button
android:id="@+id/button13"
android:layout_width="0dip"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="75" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="@+id/button21"
android:layout_width="0dip"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="00" />
<Button
android:id="@+id/button22"
android:layout_width="0dip"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="25" />
<Button
android:id="@+id/button23"
android:layout_width="0dip"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="75" />
</LinearLayout>我不知道如何处理java文件,但我正在考虑给每个button id一个值(该值当前由按钮的名称表示),并将所有值加起来,然后显示在下一页上。
发布于 2014-05-09 15:22:23
您只需将按钮上的文本转换为整数:
int value = 0;
try {
value = Integer.parseInt(button.getText().toString());
}
catch(NumberFormatException nfe) {
}发布于 2014-05-09 15:25:10
假设xml文件名为activity_main.xml。您需要一个活动类,让我们称之为MainActivity.java
MainActivity.java
public class MainActivity extends Activity implements OnClickListener{
private totalVal = 0;
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button12 = (Button) findViewById(R.id.button12);
button12.setOnClickListener(this);
// ... Do the same for the rest of the buttons
}
@Override
public void onClick(View v){
switch(v.getId(){
case R.id.button12:
int textVal = Integer.parseInt(v.getText().toString());
totalVal = totalVal + textVal;
// do whatever else you want to when the button is clicked
break;
// ... Do the same for the rest of the buttons
}您还需要一个显示您已经完成的按钮,并以类似的方式实现它。
https://stackoverflow.com/questions/23568083
复制相似问题