Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android 自定義ProgressBar

Android 自定義ProgressBar

編輯:關於Android編程

一、activity_main.xml

自定義了控件,外層是RelativeLayout,裡面是個View,通過設置View的寬度來實現進度條的前進,主要com.jltxgcy.progressbar.ProgressView要和包名一致



    

        
    


二、ProgressView.java

setProgress之所以要延遲20毫秒,是因為只有這樣才能順利獲取View的高度和寬度。自定義控件可以操作自己的View,通過onFinishInflate,來找到View,然後來操作

package com.jltxgcy.progressbar;

import android.content.Context;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.View;
import android.widget.RelativeLayout;


public class ProgressView extends RelativeLayout {
	private View mProgress;

	public ProgressView(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	@Override
	protected void onFinishInflate() {
		// TODO Auto-generated method stub
		super.onFinishInflate();
		mProgress = findViewById(R.id.progress);
	}

	public void setBackgroud() {
		mProgress.setBackgroundColor(Color.BLUE);
		
	}

	public void setProgress(final int progress) {
		postDelayed(new Runnable() {

			@Override
			public void run() {
				int width = getWidth();
				int height = getHeight();
				int curProgress = (int) (progress / 100.0 * width);
				LayoutParams params = new LayoutParams(curProgress, height);
				mProgress.setLayoutParams(params);
			}

		}, 20);

	}
}

三、MainActivity.java

通過findViewById來操作自定義ProgreeView

package com.jltxgcy.progressbar;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;

public class MainActivity extends Activity {
	private ProgressView mProgressView;
	private int progressRate;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		mProgressView = (ProgressView) findViewById(R.id.rootview);
		
		mProgressView.postDelayed(new updataProgressBar(), 500);
		
	}
	
	class updataProgressBar implements Runnable{

		@Override
		public void run() {
			mProgressView.setBackgroud();
			mProgressView.setProgress(progressRate);
			progressRate += 2;
			mProgressView.postDelayed(new updataProgressBar(), 500);	
		}
	} 

}


  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved