安卓studio显示一个按钮和一个静态文本控件,按钮按一下静态文本中的数字加一,上面也显示加一,静态文本为0,所有控件居中
时间: 2024-03-12 14:45:19 浏览: 26
好的,这个问题我可以帮你解决。
首先,我们需要在 XML 布局文件中定义一个按钮和一个 TextView 控件,并将它们居中显示。代码如下:
```xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="点击按钮" />
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/button"
android:layout_centerInParent="true"
android:text="0" />
</RelativeLayout>
```
接下来,在 Java 代码中为按钮添加点击事件,每次点击按钮时,将静态文本中的数字加一,并在 TextView 控件中显示加一后的结果。代码如下:
```java
public class MainActivity extends AppCompatActivity {
private Button mButton;
private TextView mTextView;
private int mCount = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mButton = (Button) findViewById(R.id.button);
mTextView = (TextView) findViewById(R.id.textView);
mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mCount++;
mTextView.setText(String.valueOf(mCount));
}
});
}
}
```
这样,当你点击按钮时,静态文本中的数字就会加一,同时在 TextView 控件中也会显示加一后的结果。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)