項目需求:
- 本項目是一個安卓項目,啓動頁面有一個TextView。TextView的屬性如下:
(1)寬高:包裹內容即可
(2)背景顏色:一張天空的圖片
(3)文字顯示爲:北京歡迎你,爲你開天闢地,流動中的魅力充滿着朝氣,北京歡迎你,在太陽下分享呼吸,在黃土地上刷新成績
(4)文字大小:15sp;文字顏色:colorPrimary;字體:加粗;
(5)文字顯示一行,字數較多時省略,省略號在中間; - 點擊這個TextView, 文字顯示爲“歡迎你,小明”,同時控制檯輸出“我被點擊了”
項目分析:
- 考察TextView屬性,包括省略號ellipsize屬性
- 監聽器作用:設置文字,打印日誌。
省略號的使用:
android:lines="1" <!--設置行數-->
android:ellipsize="middle" <!--省略號居中-->
一、創建android項目
1、點擊 Start a new Android Studio project
2、設置項目信息
Application name 填寫EllipsizeSet
Company Domain 填寫gui.example.com
Project location 填寫E:\AndroidStudioProjects\Ellipsize
3、勾選 Phone and Tablet
Minimum SDK選擇AP 15
4、選擇Empty Activity
5、點擊finish,這樣就創建了包含一個activity的項目
二、修改MainActivity
1.修改佈局文件activity_main.xml,添加TextView
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.gui.ellipsizeset.MainActivity">
<TextView
android:id="@+id/text_welcome"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/sky"
android:text="@string/text_welcome"
android:textSize="15sp"
android:textColor="@color/colorPrimary"
android:textStyle="bold"
android:lines="1"
android:ellipsize="middle"
/>
</RelativeLayout>
2.修改MainAcitivty,添加監聽器
- 定位text_welcome
- 添加點擊監聽器,這個監聽器的作用是修改文字
- 控制檯打印
package com.example.gui.ellipsizeset;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
//聲明text_welcome
TextView text_welcome;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//定位text_welcome
text_welcome=(TextView)findViewById(R.id.text_welcome);
//添加監聽器
text_welcome.setOnClickListener(new TextView.OnClickListener(){
@Override
public void onClick(View v) {
//設置文本
text_welcome.setText("歡迎你,小明");
//打印日誌
Log.e("text_welcome","我被點擊了");
}
});
}
}
三、運行結果
apk下載鏈接:https://pan.baidu.com/s/1L0conUQia6mw_qCu7hxEWQ
提取碼:0enc
啓動頁:(可以看到中間的省略號)
點擊文字,頁面顯示“歡迎你, 小明”
控制檯顯示: