转载请注明出处王亟亟的大牛之路
业精于勤而荒于嬉,行成于思而毁于随。
今天 上一个用runOnUiThread实现的试图内容切换功能,用Handle也可以实现,但是今天 想用这个例子让大家了解下runOnUiThread。
我们来看下他的实现
public final void runOnUiThread(Runnable action) {
if (Thread.currentThread() != mUiThread) {
mHandler.post(action);
} else {
action.run();
}
}
需要传入一个Runnable 对象,如果当前线程是用户界面线程,然后立即执行动作。如果当前线程不是用户界面线程,则该动作被张贴到用户界面线程的事件队列中。
而我们的Handle方法则是在handleMessage方法内实现业务逻辑,如果不是需要交互的UI,比较推荐runOnUiThread,因为使用更方便 -。-
OK,贴下代码(今天应用报截屏Gif那个老卡,就不截了,就是一直在那里换字,大家可以跑Demo体验下)
SwitchTextView(继承TextView就可以使用他的标签)
public class SwitchTextView extends TextView {
private boolean repeatFlag = false;
private static final long MINUTE = 60000;
private long delay = 1000; // 默认情况下时间
public SwitchTextView(Context context) {
super(context);
}
public SwitchTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public SwitchTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
// 每秒显示的字,越大刷新字越快
public SwitchTextView setWordsPerSecond(long wordsPerSecond) {
this.delay = MINUTE / wordsPerSecond;
return this;
}
public void showText(String text) {
final String words[] = text.split(" ");
final Activity activity = (Activity)getContext();
new Thread(new Runnable() {
@Override
public void run() {
while(repeatFlag) {
for(final String word : words) {
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
setText(word);
}
});
sleep(delay);
}
}
}
}).start();
}
public void sleep(long time) {
try {
Thread.sleep(time);
} catch(InterruptedException e) {
Log.e(this.getClass().getName(), "Cannot set sleep", e);
}
}
/**
* 是否可以操作
* @param repeatFlag
* @return
*/
public SwitchTextView setRepeat(boolean repeatFlag) {
this.repeatFlag = repeatFlag;
return this;
}
}
MainActivity
public class MainActivity extends AppCompatActivity {
private SwitchTextView switchTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
switchTextView = (SwitchTextView)findViewById(R.id.quick_reader_view);
switchTextView.setTextColor(Color.parseColor("#EE2E64"));
String text = "这 是 一 大 大 堆 话, 好 长 的 哦 ! !";
switchTextView.setWordsPerSecond(100).setRepeat(true).showText(text);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
实现就这些,不理解的话可以看源码:
http://yunpan.cn/cHm8scEWjT7gp 访问密码 4db7