题目
用匿名类的方式实现一个按钮事件。定义一个字符串数组资源,包含若干中国城市
名称。点击按钮时用 Toast 随机显示字符串数组资源中的一个城市名。要求:
(1) 重新设计 Toast 的布局,比如加上颜色选项或者改变字体大小等。
(2) 让 Toast 显示在屏幕上方。
答案
activity_main.xml
。
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="20dp"
>
<Button
android:id="@+id/button1"
android:layout_width="150dp"
android:layout_height="80dp"
android:layout_marginLeft="90dp"
android:layout_marginTop="300dp"
android:text="点击随机选择城市"/>
</LinearLayout>
MainActivity.java
。
package com.example.myapplication;
import android.app.Activity;
import android.os.Bundle;
import android.text.Html;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Random;
public class MainActivity extends Activity{
private Button button1=null;
void initView(){
button1=(Button)findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
String[]city=new String[]{"","北京","上海","武汉","南京","南昌","深圳","长沙","广州","昆明","贵阳","哈尔滨","吉林","苏州","杭州","郑州","南阳","青岛","石家庄","沈阳","福州","济南","成都","兰州","台北","南宁","银川","太原","长春","合肥","海口","西安","西宁","呼和浩特","拉萨","乌鲁木齐"};
int len=city.length-1;
int pos=(int)(1+Math.random()*(len));
String choose=city[pos];
Random random=new Random();
int ransize=10|random.nextInt(100);
String choose_city="<fontcolor='#000000'>"+choose+"</font>";//设定字体颜色
Toast toast=Toast.makeText(MainActivity.this,Html.fromHtml(choose_city),Toast.LENGTH_SHORT);
toast.setGravity(Gravity.TOP,60,200);
LinearLayout layout=(LinearLayout)toast.getView();
TextView textView=(TextView)layout.getChildAt(0);
textView.setTextSize(ransize);
int rancolor=0xff000000|random.nextInt(0x00ffffff);
layout.setBackgroundColor(rancolor);
toast.show();
}
});
}
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
super.setContentView(R.layout.activity_main);
initView();
}
}