2012-05-28 61 views
3

這應該是很容易做的,但不知何故經過15分鐘搜索後,我仍然無法得到答案:Android自定義視圖(TextView + Button +一些自定義行爲)?

我想製作一個自定義的Android視圖結合一個TextView和一個按鈕,加上一些自定義的行爲/方法,比方說,當我點擊按鈕時,它應該將TextView更改爲「Hello,world!」。

我知道我必須擴展View類,並在XML中設計佈局,然後做一些魔術來鏈接這兩者。你能告訴我魔術是什麼嗎?我知道如何在Activity中完成此操作,但不是在自定義View中。

EDITED 好吧,所以我發現我需要使用Inflater來使用佈局中定義的子視圖來充氣我的類。下面是我的了:

public class MyView extends View { 

private TextView text; 
private Button button; 

public MyView(Context context, AttributeSet attrs) { 
    super(context, attrs); 
    View.inflate(context, R.layout.myview, null); 
} 

@Override 
protected void onFinishInflate() { 
    super.onFinishInflate(); 
    text = (TextView) findViewById(R.id.text); 
    button = (Button) findViewById(R.id.button); 
} 
} 

然而,textbutton子視圖是空。任何想法? (這個XML非常簡單,沒有任何花哨的編輯,我只是​​從eclipse工具欄中抓取了一個TextView和一個按鈕,然後扔進去。)

+0

在此處添加您的代碼。 – Sajmon

回答

7

好的,所以我自己問題的答案是:(i)去吃晚飯, (ii)延伸LinearLayout而不是View,這使得它爲ViewGroup,因此可以傳入inflate(...)方法,但不必覆蓋onLayout(...)方法。更新的代碼將是:

public class MyView extends LinearLayout { 
    private TextView text; 
    private Button button; 

    public MyView(Context context, AttributeSet attrs) { 
     super(context, attrs); 
     View.inflate(context, R.layout.myview, this); 
    } 

    @Override 
    protected void onFinishInflate() { 
     super.onFinishInflate(); 
     text = (TextView) findViewById(R.id.text); 
     button = (Button) findViewById(R.id.button); 
    } 
} 
+0

我也想要這個功能,但不清楚。你能顯示R.layout.myview嗎? – Tahreem