页面布局
activity_text_view.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="match_parent"
android:orientation="vertical"
>
<TextView
android:id="@+id/tv_result"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/result"
android:textSize="30sp"
android:textColor="#000000"
android:gravity="center"
android:background="#FFFFFF"/>
<Button
android:id="@+id/btn_top"
android:layout_width="200dp"
android:layout_height="75dp"
android:text="@string/btn_top"
android:textSize="30sp" />
<Button
android:id="@+id/btn_bottom"
android:layout_width="200dp"
android:layout_height="75dp"
android:text="@string/btn_bottom"
android:textSize="30sp" />
<Button
android:id="@+id/btn_long"
android:layout_width="200dp"
android:layout_height="75dp"
android:text="@string/btn_long"
android:textSize="30sp" />
</LinearLayout>
strings.xml
<resources>
<string name="app_name">My Application</string>
<string name="result">这里显示点击结果</string>
<string name="btn_top">上面的按钮</string>
<string name="btn_bottom">下面的按钮</string>
<string name="btn_long">长按按钮</string>
</resources>
TextViewActivity.java
package com.example.myapplication;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
public class TextViewActivity extends AppCompatActivity implements View.OnClickListener {
private TextView tv_result;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_text_view);
tv_result = findViewById(R.id.tv_result);
findViewById(R.id.btn_top).setOnClickListener(this);
findViewById(R.id.btn_bottom).setOnClickListener(this);
findViewById(R.id.btn_long).setOnLongClickListener(view -> {
tv_result.setText("您点击了长按按钮");
return true;
});
}
@Override
public void onClick(View view) {
if(view.getId() == R.id.btn_top){
tv_result.setText("您点击了上面的按钮");
}else if (view.getId() == R.id.btn_bottom){
tv_result.setText("您点击了下面的按钮");
}
}
}