Created
April 15, 2018 08:34
-
-
Save ftnext/f5b260bf7329328a894e1ebf1374429e to your computer and use it in GitHub Desktop.
Androidでおみくじアプリ
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.graphics.Color; | |
import android.support.v7.app.AppCompatActivity; | |
import android.os.Bundle; | |
import android.util.Log; | |
import android.view.View; | |
import android.widget.Button; | |
import android.widget.TextView; | |
import java.util.Arrays; | |
import java.util.Random; | |
public class MainActivity extends AppCompatActivity { | |
private final String[] fortunes = {"大吉", "吉", "中吉", "小吉", "凶"}; | |
@Override | |
protected void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.activity_main); | |
final Button button = findViewById(R.id.drawOmikujiButton); | |
button.setOnClickListener(new View.OnClickListener() { | |
public void onClick(View v) { | |
// Code here executes on main thread after user presses button | |
Log.v("MainActivity", "Button Clicked"); | |
TextView tv = findViewById(R.id.fortuneTextView); | |
int n = fortuneIndexAtRandom(); | |
String colorString = fortuneTextColor(n); | |
tv.setText(fortunes[n]); | |
tv.setTextColor(Color.parseColor(colorString)); | |
} | |
}); | |
} | |
private int fortuneIndexAtRandom() { | |
// 配列fortunesのインデックスをランダムで返す関数 | |
Random rnd = new Random(); | |
return rnd.nextInt(fortunes.length); | |
} | |
private boolean isDaikichi(int fortune_index) { | |
// 返された運勢が大吉か判定する関数 | |
int daikichi_index = Arrays.asList(fortunes).indexOf("大吉"); | |
return fortune_index == daikichi_index; | |
} | |
private String fortuneTextColor(int fortune_index){ | |
// 運勢の文字の色を表す文字列を返す関数 | |
if (isDaikichi(fortune_index)) { | |
return "#ff0000"; | |
} else { | |
return "#808080"; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment