布局和MainActivity代码
时间: 2024-03-22 17:39:06 浏览: 52
Android代码-MainActivityUIUtil
好的,以下是一个简单的布局文件和 MainActivity 代码示例:
布局文件 activity_main.xml:
```
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center">
<TextView
android:id="@+id/scoreTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0"
android:textSize="30sp" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="@+id/increaseButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="+" />
<Button
android:id="@+id/decreaseButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="-" />
</LinearLayout>
</LinearLayout>
```
MainActivity 代码:
```
public class MainActivity extends AppCompatActivity {
private TextView scoreTextView;
private Button increaseButton;
private Button decreaseButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 获取控件
scoreTextView = findViewById(R.id.scoreTextView);
increaseButton = findViewById(R.id.increaseButton);
decreaseButton = findViewById(R.id.decreaseButton);
// 为增加按钮添加点击事件
increaseButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int score = Integer.parseInt(scoreTextView.getText().toString());
score++;
scoreTextView.setText(String.valueOf(score));
}
});
// 为减少按钮添加点击事件
decreaseButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int score = Integer.parseInt(scoreTextView.getText().toString());
score--;
scoreTextView.setText(String.valueOf(score));
}
});
}
}
```
这样就可以在 MainActivity 中实现计分牌了。
阅读全文