show code block

顯示具有 android 標籤的文章。 顯示所有文章
顯示具有 android 標籤的文章。 顯示所有文章

2017年3月22日 星期三

third-party元件(Youtube API) ─ Youtube API 簡易使用(二) 控制元件、移除SeekBar、自訂按鈕

前言:


今天來講一下YoutubePlay的控制方式。

想要自己控制PLAY、PAUSE按鈕,又或者想要自訂SeekBar。

這時候就必須要一個乾淨純粹的View ─

除了一個Time Bar 和點擊畫面上的Play、Pause外,是不是很乾淨的,很純粹。


其實也可以把所有控制按鈕都拿掉,所有的控制元件都自己設定,就像MixerBox一樣。

MixerBox就是自己控制所有元件的最好例子,單看畫面還不覺得這出自Youtube!

先讓我們看看Youtube官方文件。
https://developers.google.com/youtube/android/player/reference/com/google/android/youtube/player/YouTubePlayer.PlayerStyle

在裡面有一個mothed是專門控制Style的



YouTubePlayer.PlayerStyle

java.lang.Object
   ↳java.lang.Enum<E extends java.lang.Enum<E>>
   ↳com.google.android.youtube.player.YouTubePlayer.PlayerStyle

Overview

The different styles available for the player.

Summary

Enum values
YouTubePlayer.PlayerStyle.CHROMELESSA style that shows no interactive player controls.
YouTubePlayer.PlayerStyle.DEFAULTThe default style, showing all interactive controls.
YouTubePlayer.PlayerStyle.MINIMALA minimal style, showing only a time bar and play/pause controls.
Public methods
static YouTubePlayer.PlayerStylevalueOf(String name)
final static PlayerStyle[]values()


public static final YouTubePlayer.PlayerStyle CHROMELESS

A style that shows no interactive player controls.
這個風格完全移除和畫面的互動,所有東西都必須自訂。
ex:就如同MixerBox一樣,自訂所有畫面

public static final YouTubePlayer.PlayerStyle DEFAULT

The default style, showing all interactive controls.
正常版風格,保留了一切你在Youtube上面看的到的控制元件,包含點它們右下角的Youtube可直接跳轉到它們app觀看的原件。

public static final YouTubePlayer.PlayerStyle MINIMAL

A minimal style, showing only a time bar and play/pause controls.
最小簡化的風格,只保留TimeBar和螢幕上的播放和暫停控制元件。
ex:就如同我前言那張圖一樣,可以明顯看出pause暫停按鈕和下面的TimeBar




程式碼:

先前的程式碼請先參考:http://nikeru8.blogspot.tw/2017/03/androidyoutube-api-youtube-api.html

我們加在讀取成功後的方法內。

onInitializationSuccess


當然要讀取成功後控制這一切才有意義XDD
 @Override
    public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean wasRestored) {
        Toast.makeText(this, "onInitializationSuccess!", Toast.LENGTH_SHORT).show();
        if (youTubePlayer == null) {
            Log.d("CheckPoint", "CheckPoint youtubePlayer == null");
            return;
        }
        // Start buffering
        if (!wasRestored) {
            Log.d("CheckPoint", "CheckPoint !wasRestored");
            youTubePlayer.cueVideo(VIDEO_ID);
        }
//        youTubePlayer.setPlayerStyle(YouTubePlayer.PlayerStyle.CHROMELESS);//移除全部控制按鈕
//        youTubePlayer.setPlayerStyle(YouTubePlayer.PlayerStyle.DEFAULT);//原版
        youTubePlayer.setPlayerStyle(YouTubePlayer.PlayerStyle.MINIMAL);//移除下面的控制按鈕
    }


這邊比較值得注意的是,使用PlayerStyle.CHROMELESS時,因為移除了全部的控制按鈕,你甚至不能按下Play按鈕,要請你自己添加控制元件囉。
不然就會像一張圖片一樣卡在那。




控制元件Code:

如上所述,先在onInitializationSuccess內上程式碼。

youTubePlayer.setPlayerStyle(YouTubePlayer.PlayerStyle.CHROMELESS);



再來改變main_activity.xml的布局

main_activity.xml

<?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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.chat.a015865.youtube.MainActivity">

    <com.google.android.youtube.player.YouTubePlayerView
        android:id="@+id/player_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <LinearLayout
        android:id="@+id/video_control"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/player_view"
        android:background="#444"
        android:gravity="center_vertical"
        android:orientation="horizontal"
        android:visibility="visible"
        android:weightSum="10"
        tools:layout_editor_absoluteX="84dp"
        tools:layout_editor_absoluteY="374dp">

        <ImageButton
            android:id="@+id/play_video"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:layout_weight="1"
            android:background="@null"
            android:src="@drawable/ic_play" />

        <ImageButton
            android:id="@+id/pause_video"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:layout_weight="1"
            android:background="@null"
            android:src="@drawable/ic_pause" />

        <SeekBar
            android:id="@+id/video_seekbar"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:layout_weight="6"
            android:max="100"
            android:progress="0" />

        <TextView
            android:id="@+id/play_time"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:layout_weight="2"
            android:text="--:--"
            android:textColor="@android:color/white" />
    </LinearLayout>
</RelativeLayout>





MainActivity.java

public class MainActivity extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener, View.OnClickListener {


    public static final String API_KEY = "AIzaSyAPThx6WbAxjnX2En0qtf9OhD80tUcp380";

    //https://www.youtube.com/watch?v=
    public static final String VIDEO_ID = "qZIWO9TqvIA";

    private YouTubePlayer mYoutubePlayer;
    private View mPlayButtonLayout;
    private TextView mPlayTimeTextView;

    private Handler mHandler = null;
    private SeekBar mSeekBar;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final YouTubePlayerView mYoutubePlayerView = (YouTubePlayerView) findViewById(R.id.player_view);
        mYoutubePlayerView.initialize(API_KEY, this);
        initView();
        mPlayButtonLayout = findViewById(R.id.video_control);
        findViewById(R.id.play_video).setOnClickListener(this);
        findViewById(R.id.pause_video).setOnClickListener(this);

        mPlayTimeTextView = (TextView) findViewById(R.id.play_time);
        mSeekBar = (SeekBar) findViewById(R.id.video_seekbar);
        mSeekBar.setOnSeekBarChangeListener(mVideoSeekBarChangeListener);
        mHandler = new Handler();
    }

    private void initView() {

    }

    @Override
    public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean wasRestored) {
        Toast.makeText(this, "onInitializationSuccess!", Toast.LENGTH_SHORT).show();
        mYoutubePlayer = youTubePlayer;
        if (youTubePlayer == null) {
            Log.d("CheckPoint", "CheckPoint youtubePlayer == null");
            return;
        }
        // Start buffering
        if (!wasRestored) {
            Log.d("CheckPoint", "CheckPoint !wasRestored");
            youTubePlayer.cueVideo(VIDEO_ID);
        }
        youTubePlayer.setPlayerStyle(YouTubePlayer.PlayerStyle.CHROMELESS);
//        youTubePlayer.setPlayerStyle(YouTubePlayer.PlayerStyle.DEFAULT);//原版
//        youTubePlayer.setPlayerStyle(YouTubePlayer.PlayerStyle.MINIMAL);//移除下面的控制按鈕

        youTubePlayer.setPlayerStateChangeListener(mPlayerStateChangeListener);//影片在run時的狀態
        youTubePlayer.setPlaybackEventListener(mPlaybacckEventListener);
    }

    YouTubePlayer.PlaybackEventListener mPlaybacckEventListener = new YouTubePlayer.PlaybackEventListener() {
        @Override
        public void onPlaying() {
            mHandler.postDelayed(runnable, 100);
            displayCurrentTime();
        }

        @Override
        public void onPaused() {
            mHandler.removeCallbacks(runnable);
        }

        @Override
        public void onStopped() {
            mHandler.removeCallbacks(runnable);
        }

        @Override
        public void onBuffering(boolean b) {

        }

        @Override
        public void onSeekTo(int i) {
            Log.d("CheckPoint", "CheckPoint i = " + i);
            mHandler.postDelayed(runnable, 100);
        }
    };
    YouTubePlayer.PlayerStateChangeListener mPlayerStateChangeListener = new YouTubePlayer.PlayerStateChangeListener() {
        @Override
        public void onLoading() {

        }

        @Override
        public void onLoaded(String s) {

        }

        @Override
        public void onAdStarted() {

        }

        @Override
        public void onVideoStarted() {
            displayCurrentTime();
        }

        @Override
        public void onVideoEnded() {

        }

        @Override
        public void onError(YouTubePlayer.ErrorReason errorReason) {

        }
    };

    @Override
    public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
        Toast.makeText(this, "Failed to initialize.", Toast.LENGTH_LONG).show();
    }

    SeekBar.OnSeekBarChangeListener mVideoSeekBarChangeListener = new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(final SeekBar seekBar, final int progress, boolean fromUser) {
            long lengthPlayed = (mYoutubePlayer.getDurationMillis() * progress) / 100;
            mYoutubePlayer.seekToMillis((int) lengthPlayed);
            seekBar.setProgress(progress);
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }
    };

    private void displayCurrentTime() {
        if (mYoutubePlayer == null) return;
        String formattedTime = formatTime(mYoutubePlayer.getDurationMillis() - mYoutubePlayer.getCurrentTimeMillis());
        mPlayTimeTextView.setText(formattedTime);
    }

    private String formatTime(int millis) {
        int seconds = millis / 1000;
        int minutes = seconds / 60;
        int hours = minutes / 60;
        return (hours == 0 ? "- - : " : formatS(hours) + ":") + formatS(minutes % 60) + ":" + formatS(seconds % 60);
    }

    private String formatS(int x) {
        String s = "" + x;
        if (s.length() == 1)
            s = "0" + s;
        return s;
    }


    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            displayCurrentTime();

            mHandler.postDelayed(this, 100);
        }
    };

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.play_video:
                if (null != mYoutubePlayer && !mYoutubePlayer.isPlaying())
                    mYoutubePlayer.play();
                break;
            case R.id.pause_video:
                if (null != mYoutubePlayer && mYoutubePlayer.isPlaying())
                    mYoutubePlayer.pause();
                break;
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        mYoutubePlayer.release();
        mYoutubePlayer = null;
        mHandler.removeCallbacks(runnable);
    }
}


edit(2017/03/27)
上面無法和seekbar連動,當你移動seekbar影片會跟著移動,但影片再撥放的時候seekbar無法連動。
我試過RunOnUiThread設定seekbar會發生錯誤。
我修好的話會在上傳新code







third-party元件(Youtube API)─ Youtube API 簡易使用、匯入專案lib

前言:


此篇我們來實作內崁Youtube影音的功能。

為什麼不用WebView直接內崁?

因為WebView內崁的方式很醜阿。
會變下圖這樣


我不想要下面這些東西,想要單純的只有影片,其他東西我可以自由地運用。

當然還有一些比較特別的使用方式。

像是MixerBox,就是拿這個在營利。







1、首先先去這網頁下載他們的api
https://developers.google.com/youtube/android/player/downloads/


下載下來會是一個.zip檔案那要怎麼import到android studio內呢?



2、先解壓縮吧。
然後打開資料夾找到libs檔案我們需要的東西在裡面。

你會找到YouTubeAndroidPlayerApi.jar這的檔案。

然後找到你的專案在最最上層開一個libs資料夾,以後好方便管理你import的東西。
3、回到Android Studio內,右上方File >> Project Structure...


按下去之後,找到你自己專案,案ok


我們就可以使用Youtube API囉




程式碼:

先給網路權限吧!

AndroidManifest

<uses-permission android:name="android.permission.INTERNET" />


1、增加YouTubePlayerView到xml內

在main_activity.java內設定View

main_activity.java

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.chat.a015865.youtube.MainActivity">

    <com.google.android.youtube.player.YouTubePlayerView
        android:id="@+id/player_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</android.support.constraint.ConstraintLayout>



2、初始化YouTubePlayerView(Initialize)

MainActivity.java內,在要使用YouTubePlayerView的activity都一定要改extends繼承變成YouTubeBaseActivity,並且imp;ements YouTubePlayer.OnInitializedListener。

implements YouTubePlayer.OnInitializedListener 之後,請implements methods

拿到onInitializationSuccess(初始化成功)和onInitializationFailure(初始化失敗)

在onCreate內初始化YouTubePlayerView

mYoutubePlayerView.initialize(API_KEY, this);

API_KEY目前用不到,可以先隨便給值。

Youtube網址的格式 https://www.youtube.com/watch?v= xxxxxx 後面的的xxxxxx可以改變你想看的頻道。試著去YOUTUBE上找你喜愛的頻道,COPY後面的xxxxxx回到MainActivity.java改變VEDIO_ID,就可以改變你要看的東西。


MainActivity.java

public class MainActivity extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener {


    public static final String API_KEY = "htyhry";

    //https://www.youtube.com/watch?v=
    public static final String VIDEO_ID = "OsUr8N7t4zc";
    private YouTubePlayerView mYoutubePlayerView;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mYoutubePlayerView = (YouTubePlayerView) findViewById(R.id.player_view);
        mYoutubePlayerView.initialize(API_KEY, this);
    }

    @Override
    public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean wasRestored) {
        Toast.makeText(this, "onInitializationSuccess!", Toast.LENGTH_SHORT).show();
        if (youTubePlayer == null) {
            Log.d("CheckPoint", "CheckPoint youtubePlayer == null");
            return;
        }
        
        if (!wasRestored) {
            Log.d("CheckPoint", "CheckPoint !wasRestored");
            youTubePlayer.cueVideo(VIDEO_ID);
        }
    }

    @Override
    public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
        Toast.makeText(this, "Failed to initialize.", Toast.LENGTH_LONG).show();

    }
}


這時候你就可以開始跑你的專案了,五月天的頑固就出現拉!


3、控制 YouTubePlayer 事件

其中還有一些控制YouTubePlayer的方法,像是可以再按暫停的同時,加入你要的廣告....之類的。
在MainAcitivity.java內 >> onInitializationSuccess這裡面加入這個方法,可以控制Loading、onLoaded、onAdStarted....等等。

 youTubePlayer.setPlayerStateChangeListener(new YouTubePlayer.PlayerStateChangeListener() {
            @Override
            public void onLoading() {
                Log.d("CheckPoint", "CheckPoint onLoading");
            }

            @Override
            public void onLoaded(String s) {
                Log.d("CheckPoint", "CheckPoint onLoaded");
            }

            @Override
            public void onAdStarted() {
                Log.d("CheckPoint", "CheckPoint onAdStarted");
            }

            @Override
            public void onVideoStarted() {
                Log.d("CheckPoint", "CheckPoint onVideoStarted");
            }

            @Override
            public void onVideoEnded() {
                Log.d("CheckPoint", "CheckPoint onVideoEnded");
            }

            @Override
            public void onError(YouTubePlayer.ErrorReason errorReason) {
                Log.d("CheckPoint", "CheckPoint onError = " + errorReason);
            }
        });





文獻:


Demo:











2017年3月13日 星期一

Android元件 ─ PointOfOrigin 點擊後彈出視窗

前言:


接續前一篇RecyclerView的範例。

可直接下載範本來做修改。

這次做的是類似PopupView的彈跳效果,但自帶動畫,更為方便!






重點程式碼:

本次更動簡易流程 ─



drawable內的loading圖片下載:
https://cdn-images-1.medium.com/max/800/0*-IoUUPvNx3NihgGi.gif

我們直接從RecyclerViewAdapter.java內的
onBindViewHolder裡面的點擊事件開啟我們的第一步:
  @Override
    public void onBindViewHolder(final RecyclerViewAdapter.MyHolder holder, final int position) {
        Glide.with(mContext).load(itemsData[position].getImageUrl())
                .error(R.drawable.loading)
                .placeholder(R.drawable.tool)
                .into(holder.mImageView);
      holder.mTextView.setText(itemsData[position].getTitle());

      holder.setOnItemClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
              //設定你點擊每個Item後,要做的事情
            }
        });
    }


接下來實作PointOfOrigin 點擊後彈出視窗
先額外創建一個Activity,我命名為secondActivity.java 和 activity_second.xml
activity_second.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="bottom"
    android:gravity="bottom"
    android:orientation="vertical">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="150dp"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:layout_marginTop="20dp"
        android:gravity="center"
        android:text="Point Of Origin Demo \n\n返回鍵返回" />

    <ImageView
        android:id="@+id/image"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:adjustViewBounds="true"
        android:cropToPadding="false"
        android:scaleType="fitCenter"
        android:src="@drawable/loading"
        android:transitionName="tImage" />
</LinearLayout>

secondActivity.java
public class SecondActivity extends Activity {
    private static final String TAG = "SecondActivity";

    private ImageView image;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);

        image = (ImageView) findViewById(R.id.image);
        if (getIntent() != null) {
            Log.i(TAG, "CheckPoint getIntent() != null" + getIntent());
//            int res = getIntent().getIntExtra("imageRes", 0);
            String res = getIntent().getStringExtra("imageRes");

            if (res != null)
                Glide.with(this).load(res).placeholder(R.drawable.loading).into(image);
        } else {
            Log.i(TAG, "CheckPoint onCreate:  getIntent()==null");
        }
    }
}


創建好後,在RecyclerViewAdapter.java內的onBindViewHolder裡面
 holder.setOnItemClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 宣告一組配對,底下我們讓MainActivity裡[RecyclerView]->[ItemList]->[ImageView]和SecondActivity裡的ImageView作成一組配對
               Pair imagePair = Pair.create((View) holder.mImageView, "tImage");
                Intent transitionIntent = new Intent(mContext, SecondActivity.class);
                transitionIntent.putExtra("imageRes", itemsData[position].getImageUrl());
                // 製作成 Material Design 需要的 ActivityOptionsCompat
                ActivityOptionsCompat options = ActivityOptionsCompat.makeSceneTransitionAnimation((Activity) mContext, imagePair);
                ActivityCompat.startActivity((Activity) mContext, transitionIntent, options.toBundle());
            }
        });
裡面的tImage是連接 secondActivity.java 裡面imageView的key




完成!





完整程式碼就不一一張貼了,詳情請見Demo:





Android元件 ─ RecyclerView、Item點擊事件 onClick

前言:

如果你是要找像是ListView的setOnItemClickListener 可以看我的這篇。

Android方法(RecyclerView) — RecyclerView外接到activity點擊事件

我的Android年齡實在很短,在我接觸Android的時候,已經是RecyclerView和ListView並存的時候了。

簡而言之RecyclerView的回收機制和各種都趨近完善,比ListView強大很多。
RecyclerView最大的好處就是各種強大的排版方式。

RecylerView在使用上多了幾項必須的東西。
必須而外創建LinearManager ,這可以幫助你不用一直findViewById節省不必要的資源。
ViewHolder也變成強制必須加上的方法。




完全程式碼:

免不了的import

//主要是這一個
compile 'com.android.support:recyclerview-v7:25.2.0'
//這個是網路下載圖片的IMPORT
 compile 'com.github.bumptech.glide:glide:3.7.0'

我是使用Gidle在讀取圖片:


第一件事情是給權限,我在RecyclerView內的圖片是網路下載
<uses-permission android:name="android.permission.INTERNET"/>

此次動到的xml and java



在 res/value/drawable 內丟一張讀取中(loading)要使用到的圖片

activity_main.xml

<?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.chat.a015865.pointoforigin.MainActivity">

 <android.support.v7.widget.RecyclerView
     android:id="@+id/recycler_view"
     android:layout_width="match_parent"
     android:layout_height="match_parent"/>
</RelativeLayout>


item.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="100dp"
    android:orientation="horizontal">

    <ImageView
        android:id="@+id/image_view"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_margin="5dp" />

    <TextView
        android:id="@+id/text_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="hello" />
</LinearLayout>

MainActivity.java

    
public class MainActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
    private RecyclerViewAdapter mRecyclerViewAdapter;
    private Context mContext;
    private String[] urlList;
   private ItemData[] itemsData;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mContext = this;
        initView(); //設定View  (Eg:findViewById)
        initSet(); //設定功能 (Eg:setAdapter)
        initListener(); //設定點擊 (eg:onClick)
    }
    private void initListener(){

    }

    private void initView() {
        mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
    }

    private void initSet() {
        setData();
        mRecyclerViewAdapter = new RecyclerViewAdapter(mContext);
        LinearLayoutManager llm = new LinearLayoutManager(this);
        llm.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(llm);
        mRecyclerView.setAdapter(mRecyclerViewAdapter);
        mRecyclerViewAdapter.upData(itemsData);
    }

    private void setData() {
        urlList = new String[]{
                "http://www.jrtstudio.com/sites/default/files/ico_android.png",
                "https://pbs.twimg.com/profile_images/616076655547682816/6gMRtQyY.jpg",
                "http://cdn.bgr.com/2012/11/android-icon.jpg?quality=98&strip=all",
                "http://www.fastbooting.com/uploads/5/5/9/9/55994511/1474140_orig.png",
                "http://www.pendidikan-diy.go.id/dinas_v4/img/up_down/Android.png",
        };
        itemsData = new ItemData[]{
                new ItemData("abc", urlList[0]),
                new ItemData("defaf", urlList[1]),
                new ItemData("erhrh", urlList[2]),
                new ItemData("GDERGE", urlList[3]),
                new ItemData("EGER", urlList[4]),
                new ItemData("QHRE", urlList[0]),
                new ItemData("QEHE", urlList[1]),
                new ItemData("RTHRT", urlList[2]),
                new ItemData("YJTEY", urlList[3]),
                new ItemData("RGEW", urlList[4])
        };
    }
}

RecyclerViewAdapter.java

/**
 * Created by 015865 on 2017/3/13.
 */

public class RecyclerViewAdapter extends RecyclerView.Adapter {

    private ItemData[] itemsData;
    private Context mContext;

    public RecyclerViewAdapter(Context context) {
        mContext = context;
    }

    public void upData(ItemData[] item) {
        itemsData = item;
        notifyDataSetChanged();

    }

    public class MyHolder extends RecyclerView.ViewHolder {
        private ImageView mImageView;
        private TextView mTextView;

        public MyHolder(View itemView) {
            super(itemView);
            mImageView = (ImageView) itemView.findViewById(R.id.image_view);
            mTextView = (TextView) itemView.findViewById(R.id.text_view);
        }
    }

    @Override
    public RecyclerViewAdapter.MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item, parent, false);
        MyHolder mh = new MyHolder(view);
        return mh;
    }

    @Override
    public void onBindViewHolder(RecyclerViewAdapter.MyHolder holder, int position) {
        Glide.with(mContext).load(itemsData[position].getImageUrl())
                .error(R.drawable.ico_android)
                .placeholder(R.drawable.tool)
                .into(holder.mImageView);
        holder.mTextView.setText(itemsData[position].getTitle());
    }

    @Override
    public int getItemCount() {
        return itemsData == null ? 0 : itemsData.length;
    }
}

ItemData.java

public class ItemData {
    private String title;
    private String imageUrl;

    public ItemData(String title, String imageUrl) {
        this.title = title;
        this.imageUrl = imageUrl;
        Log.d("ItemData", "CheckPoint imageUrl=" + imageUrl);
    }

    public String getTitle() {
        return title;
    }

    public String getImageUrl() {
        return imageUrl;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public void setImageUrl(String imageUrl) {
        this.imageUrl = imageUrl;
    }
}




更新(2017/03/14)
RecyclerView的點擊事件item

重點程式碼:

首先先做出RecyclerView每個Item的點擊事件。
兩個地方需要更改!

我們從MyHolder下去著手。

RecyclerViewAdapter.java

1、MyHolder讓每個hold住的畫面都有點擊事件
 public class MyHolder extends RecyclerView.ViewHolder {
        private ImageView mImageView;
        private TextView mTextView;
        private View view;

        public MyHolder(View itemView) {
            super(itemView);
            view = itemView;
            mImageView = (ImageView) itemView.findViewById(R.id.image_view);
            mTextView = (TextView) itemView.findViewById(R.id.text_view);
        }

        public void setOnItemClick(View.OnClickListener l) {
            this.view.setOnClickListener(l);
        }
    }

2、再從onBindViewHolder下手,設定每個點擊事件要做的事情
 
 @Override
    public void onBindViewHolder(final RecyclerViewAdapter.MyHolder holder, final int position) {
        Glide.with(mContext).load(itemsData[position].getImageUrl())
                .error(R.drawable.loading)
                .placeholder(R.drawable.tool)
                .into(holder.mImageView);

        holder.mTextView.setText(itemsData[position].getTitle());

        holder.setOnItemClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
              //設定你點擊每個Item後,要做的事情
   
            }
        });
    }



這就能完成每次的點擊事件。

Demo:
https://drive.google.com/open?id=0Byk75IYx-dKXR0lnZW9RQU90MDQ

網路上方式很多也超級詳細,不再贅述
小鰻:http://lp43.blogspot.tw/2014/08/recyclerviewandroid-studio.html

2017年3月1日 星期三

Android元件(WebView) ─ 內崁網路瀏覽器、和webView做溝通

前言:


讓網頁上的網路像是你自己的App一樣!

內崁式,很多公司因為懶得寫雙平台,會直接使用Mobile Web的方式直接在雙平台IOS和Android內崁WebView,但因為是內崁的,會造成使用者在使用上不流暢!
會有不太好的使用者體驗。
這邊用臉書網址當作示範





重點程式碼:

想看webView有什麼東西可以用可以查原始文件內的Public mothed
https://developer.android.com/reference/android/webkit/WebView.html

可以直接複製貼在OnCreate內
//1、先設定元件findViewById
 WebView  mWebView = (WebView) findViewById(R.id.webview);

//2、這是設定內崁,沒有這一行系統會直接呼叫出瀏覽器開啟你指定的網址
mWebView.setWebViewClient(mWebViewClient);

//3、Setting對WebView做設定,以下是我常用的WebView設定,我就直接複製上來了
 WebSettings websettings = mWebView.getSettings();
       websettings.setSupportZoom(true); //啟用內置的縮放功能
       websettings.setBuiltInZoomControls(true);//啟用內置的縮放功能
       websettings.setDisplayZoomControls(false);//讓縮放功能的Button消失
       websettings.setJavaScriptEnabled(true);//使用JavaScript
       websettings.setAppCacheEnabled(true);//設置啟動緩存
       websettings.setSaveFormData(true);//設置儲存
       websettings.setAllowFileAccess(true);//啟用webview訪問文件數據
       websettings.setDomStorageEnabled(true);//啟用儲存數據
//4、loadUrl讀取網頁String
mWebView.loadUrl("http://nikeru8.blogspot.tw/");


很簡單吧!





完整程式碼:

activity_main.xml


<?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"
    tools:context="com.chat.a015865.webview.MainActivity">

    <WebView
        android:id="@+id/webview_show"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</RelativeLayout>




MainActivity.java


public class MainActivity extends AppCompatActivity {

    private WebView mWebView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mWebView=(WebView)findViewById(R.id.webview_show);
        WebSettings websettings = mWebView.getSettings();
        websettings.setSupportZoom(true);
        websettings.setBuiltInZoomControls(true);
        websettings.setDisplayZoomControls(false);
        websettings.setJavaScriptEnabled(true);
        websettings.setAppCacheEnabled(true);
        websettings.setSaveFormData(true);
        websettings.setAllowFileAccess(true);
        websettings.setDomStorageEnabled(true);
        mWebView.setWebViewClient(new WebViewClient());

        mWebView.loadUrl("http://nikeru8.blogspot.tw/");
    }
}



需要注意的部分:

loadUrl內的網址不可以是:www.google.com   
請給https://www.google.com.tw/



 (補充:2017/09/15)兩件事情

一、 網頁沒彈出應該彈出的Dialog?

webView.setWebChromeClient(new WebChromeClient());

如果你的webView裡面有個按鈕點下去應該彈出網頁那種Dialog 。但是消失了!?
這行可以救你。

二、如何和webView做溝通?



 WebViewClient mWebViewClient = new WebViewClient() {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            Log.d("CHECK URL", "url= " + url);
            
            return true;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            // TODO Auto-generated method stub
            super.onPageFinished(view, url);
        }
    };
 
在shouldOverrideUrlLoading內的url是你現在webView的網址
你可以使用string.contains來抓取網址內的關鍵字。
舉個例子在shouldOverrideUrlLoading內,使用url如果url內有Login的字眼,可以直接跳轉到你自己App內的登入頁面
登入完成後,在使用onActivityResult和webview做溝通。
if (url.contains("Login")){
    //TODO  轉到你自己寫的登入頁面}

三、開啟facebook live的方式

http://nikeru8.blogspot.tw/2017/09/androidwebview-webviewufacebook.html

Demo:

https://drive.google.com/open?id=0Byk75IYx-dKXVWJkQnlSSUp5VDQ


Android元件 ─ EditText和TextView連動

前言:

效果如下



EditText和TextView的連動,可以運用在很多地方!
分享給你們。



實作 :

1、先在xml做出TextView和EditText
2、在MainActivity.java內指定上述兩個東西的元件(findViewById)
3、EditText此次的重點程式碼:
 mEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                 //do something
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                //do something               
             mText.setText(charSequence);
             }

            @Override
            public void afterTextChanged(Editable editable) {
               //do something
            }
        });


/**TextWatcher
*

*beforeTextChanged 在edit改變之前要做的事情

*onTextChanged  在edit改變中要做的事情

*afterTextChanged 在edit改變後要做的事情

*/

我們要改動的就是改變中的這個變數!



完整程式碼:


activity_main.xml

<?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:paddingTop="5dp"
    tools:context="com.chat.a015865.playedit.MainActivity">

    <TextView
        android:id="@+id/show_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:gravity="center"
        android:padding="20dp"
        android:text="Content" />

    <EditText
        android:id="@+id/show_edit"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/show_text"
        android:layout_centerInParent="true"
        android:hint="TypeSomething" />
</RelativeLayout>

MainActivity.java

public class MainActivity extends AppCompatActivity {

    private EditText mEdit;
    private TextView mText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mEdit = (EditText) findViewById(R.id.show_edit);
        mText = (TextView) findViewById(R.id.show_text);

        mEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                mText.setText(charSequence);
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
    }
}





Demo:



影片中的TextView邊框在這:http://nikeru8.blogspot.tw/2017/03/textview.html







2017年2月17日 星期五

Android元件:SharedPreferences ─ 儲存資料的好幫手



今日時做影片:





主要程式碼:
SharedPreferences sharedPreferences = getSharedPreferences(String name, int mode);

String name:是你要儲存在手機內的檔案名稱。
Int mode:是你儲存的方式,通常都是使用MODE_PRIVATE(除了你這個app其他app不能使用)

各種MODE
Sr.No
Mode & description
1
MODE_APPEND
This will append the new preferences with the already existing preferences
2
MODE_ENABLE_WRITE_AHEAD_LOGGING
Database open flag. When it is set , it would enable write ahead logging by default
3
MODE_MULTI_PROCESS
This method will check for modification of preferences even if the sharedpreference instance has already been loaded
4
MODE_PRIVATE
By setting this mode, the file can only be accessed using calling application
5
MODE_WORLD_READABLE
This mode allow other application to read the preferences
6
MODE_WORLD_WRITEABLE
This mode allow other application to write the preferences


儲存方式:
SharedPreferences sharedPreferences = getSharedPreferences(data, MODE_PRIVATE);

假設你在EditText內打了一串東西想之後打開app之後還留存。


sharedPreferences.edit()
     .putString(“I_WANT_TO_SAVE_EDIT”, OneEdit.getText().toString())
     .apply();

呼叫sharedPreferences在後面加一個eidt()  (英文大補帖: edit 編輯 )
仔使用putstring 加入你要處存的東西
apply 使它生效(英文大補帖: apply  始生效 )
這就存起來了。
它會存在叫“I_WANT_TO_SAVE_EDIT”的檔案內。

讀取方式:


OneEdit.setText(sharedPreferences.getString(“I_WANT_TO_SAVE_EDIT”, ""));




同場加映

固定Switch開關的問題。

當我讓SWITCH開關成開啟狀態,當下次開啟APP時,要如何保持在開啟狀態呢?


當然是先在xml 內畫一個 switchButton


activity_main.xml
  <Switch
        android:id="@+id/switch_button"
        android:layout_marginTop="10dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal" />

MainActivity.java

先設定元件
private Switch switch_buton;

指定給xml
switch_buton = (Switch) findViewById(R.id.switch_button);

設定SwitchButton的點擊方式

 switch_buton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (switch_buton.isChecked()) {
                    //如果SwitchButton開啟 do something

                    //儲存
                    sharedPreferences.edit().putBoolean(switchField, true).apply();
                    Log.d(handle, "onClick isChecked switchField= is Open");
                } else {
                    //如果SwitchButton關閉 do something

                    //儲存
                    sharedPreferences.edit().putBoolean(switchField, false).apply();
                    Log.d(handle, "onClick isClosed switchField= is Closed");
                }
            }
        });

然後再OnCreate的地方丟入,這行是指你開啟APP時,讀取你存在sharedPreferences內的SWITCH 狀態。
switch_buton.setChecked(sharedPreferences.getBoolean(switchField, false));

這樣SwitchButton就可以正常開關囉!




完整程式碼:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
    tools:context="com.chat.a015865.sharedpreferences.MainActivity">

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="1" />

    <EditText
        android:id="@+id/oneField"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
      />

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="2" />

    <EditText
        android:id="@+id/twoField"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
       />

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="3" />

    <EditText
        android:id="@+id/threeField"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
       />

    <Switch
        android:id="@+id/switch_button"
        android:layout_marginTop="10dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal" />

    <Button
        android:id="@+id/close_button"
        android:text="關閉app"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>



MainActivity.java
public class MainActivity extends AppCompatActivity {

    private static final String handle = MainActivity.class.getSimpleName();

    private EditText OneEdit, TWO, THREE;
    private Context context;
    private Button close_Button;
    private Activity activity;

    private SharedPreferences sharedPreferences;
    private static final String data = "DATA";
    private static final String helloField = "ONE_STATE";
    private static final String twoField = "TWO_STATE";
    private static final String threeField = "THREE_SATE";
    private static final String switchField = "SWITCH_STATE";

    private Switch switch_buton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        context = this;
        activity = this;
        initView();
        initSet();
        readData();//讀取
    }

    private void initView() {
        close_Button = (Button) findViewById(R.id.close_button);
        sharedPreferences = getSharedPreferences(data, MODE_PRIVATE);
        switch_buton = (Switch) findViewById(R.id.switch_button);
        OneEdit = (EditText) findViewById(R.id.oneField);
        TWO = (EditText) findViewById(R.id.twoField);
        THREE = (EditText) findViewById(R.id.threeField);
    }

    private void initSet() {
        switch_buton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (switch_buton.isChecked()) {
                    //如果SwitchButton開啟 do something

                    //儲存
                    sharedPreferences.edit().putBoolean(switchField, true).apply();
                    Log.d(handle, "onClick isChecked switchField= is Open");
                } else {
                    //如果SwitchButton關閉 do something

                    //儲存
                    sharedPreferences.edit().putBoolean(switchField, false).apply();
                    Log.d(handle, "onClick isClosed switchField= is Closed");
                }
            }
        });

        close_Button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

    public void readData() {//讀取
        switch_buton.setChecked(sharedPreferences.getBoolean(switchField, false));
        OneEdit.setText(sharedPreferences.getString(helloField, ""));
        TWO.setText(sharedPreferences.getString(twoField, ""));
        THREE.setText(sharedPreferences.getString(threeField, ""));
    }

    public void saveData() {//儲存
        sharedPreferences.edit()
                .putString(helloField, OneEdit.getText().toString())
                .putString(twoField, TWO.getText().toString())
                .putString(threeField, THREE.getText().toString())
                .apply();
    }


    @Override
    protected void onPause() {
        super.onPause();
        Log.d(handle, "onPause()");
        saveData();
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.d(handle, "onStop()");
        saveData();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d(handle, "onDestroy()");
        saveData();
    }
}





Demo下載:
https://drive.google.com/open?id=0Byk75IYx-dKXMDZZcHFHY3U4SXc
有問題請發問囉!


協程(coroutine) - 協程為什麼要學它?

 Coroutine 協程 再強調一次 協程就是由kotlin官方所提供的線程api //Thread Thread { }.start() //Executor val execu...