android自訂控制項(六) 重新整理

來源:互聯網
上載者:User

三種得到LinearInflater的方法

a. LayoutInflater inflater = getLayoutInflater();

b. LayoutInflater localinflater =
  (LayoutInflater)context.getSystemService
(Context.LAYOUT_INFLATER_SERVICE); 

c. LayoutInflater inflater = LayoutInflater.from(context);

onDraw 方法繪圖,invalidate重新整理介面。

:

點擊一下換顏色

    

onDraw畫完圖後,給控制項設定點擊事件 ,將參數傳到控制項裡,然後invalidate重新整理

1.onDraw畫圖,並增加changeColor方法

public class CusView3 extends View {private int color = 0;public CusView3(Context context, AttributeSet attrs) {super(context, attrs);}@Overrideprotected void onDraw(Canvas canvas) {super.onDraw(canvas);Paint mPaint = new Paint();if (color > 2) {color = 0;}switch (color) {case 0:mPaint.setColor(Color.GREEN);break;case 1:mPaint.setColor(Color.RED);break;case 2:mPaint.setColor(Color.BLUE);break;default:break;}mPaint.setStyle(Style.FILL);mPaint.setTextSize(35.0f);canvas.drawText("點擊我重新整理", 10, 60, mPaint);}public void changeColor() { //為了讓外面調用color++;}}

2.布局

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:orientation="vertical"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    ><xue.test.CusView3android:id="@+id/cusview3"android:layout_width="wrap_content"android:layout_height="wrap_content"></xue.test.CusView3></LinearLayout>

3.畫圖後 給控制項設定點擊事件 ,將參數傳到控制項裡,然後invalidate重新整理

public class TestCustomViewActivity extends Activity {@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);view3 = (CusView3) findViewById(R.id.cusview3);// 點擊事件view3.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {Message message = new Message();message.what = 1;myHandler.sendMessage(message);}});}Handler myHandler = new Handler() {// 接收到訊息後處理public void handleMessage(Message msg) {switch (msg.what) {case 1:// 調用方法view3.changeColor();// 重新整理方法view3.invalidate();break;}super.handleMessage(msg);}};private CusView3 view3;}

至於自訂控制項占整屏的問題,可能需要用layoutparams

源碼下載: http://download.csdn.net/detail/ethan_xue/4152203

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.