iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 10
0
Software Development

Java 與 Kotlin 入門系列 第 10

[Day10]ListViewr設計

ListView活用,且增加色彩記憶功能。

Imgur
我們想要調色,首先創建一個ColorActivity,那他的xml如上圖。
設計成一個HorizontalScrollView,水平滾動視圖,是一個可以水平方向滾動的佈局容器,允許它大於物理顯示。
水平滾動視圖(HorizontalScrollView)是一個框佈局(FrameLayout),這意味著你應該將一個包含全部滾動內容的子項放進去。
該子項本身可以是一個帶有複雜對象的佈局管理器(layout manager)

Imgur

for (Colors color : Colors.values())

這是指,foreach也就是color這個變數會跑Colors這個class裡面的所有values
再來codebutton

LinearLayout.LayoutParams layout =
new LinearLayout.LayoutParams(128, 128);

我們的大小為設置(height:128,width:128)

layout.setMargins(6, 6, 6, 6);

邊距。

button.setId(color.parseColor());
button.setLayoutParams(layout);
button.setBackgroundColor(color.parseColor());
button.setOnClickListener(listener);
color_gallery.addView(button);
  • 將每個呈現的button以顏色來設置id
  • 將設計好的layout塞入button
  • button設計顏色。
  • button註冊觸發事件。
  • 最後將這個button加入畫面View(linearlayout)

Imgur
寫一個class ColorListener實作View.OnClickListener

預設顏色部分

String action = ColorActivity.this.getIntent().getAction(); 

if (action!=null&&action.equals("android.intent.action.CHOOSE_COLOR")) {
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(ColorActivity.this).edit();
editor.putInt("DEFAULT_COLOR", view.getId());
editor.commit();
finish();}
  • 首先一個字串action=拿到intent過來的動作。
  • 判斷著個動作是否為空值同時判斷他是不是"android.intent.action.CHOOSE_COLOR",這個自己加的action是的話,繼續往下面。
    -創建一個SharedPreferences.Editor為了存入值,key為"DEFAULT_COLOR"value則是view拿到的對應Id
  • commitSharedPreferences.Editor溝通(存放)
  • 最後finish()結束這個Activity

自己選顏色部分

else {
Intent result = new Intent();
result.putExtra("colorId", view.getId());
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(ColorActivity.this).edit();
editor.putInt("DEFAULT_COLORS", view.getId());
editor.commit();
setResult(RESULT_OK, result);
finish();}
  • new 一個Intent
  • 放入值keycolorIdvalue為使用者點的button對應到的Id,也就是我們剛剛設置的Id
  • 一樣使用SharedPreferences.Editor存放,key"DEFAULT_COLORS"value一樣是view拿到的對應Id
  • commitSharedPreferences.Editor溝通(存放)
  • 最後finish()結束這個Activity

上一篇
[Day09]ListView應用
下一篇
[Day11]ListView設計-02
系列文
Java 與 Kotlin 入門30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言