16

一個活動,您可以通過以下方式編程方式創建的LinearLayout:如何以編程方式創建自定義視圖的佈局?

public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

    LinearLayout ll = new LinearLayout(this); 
    ll.setOrientation(LinearLayout.VERTICAL); 
    ll.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); 

    TextView tv1 = new TextView(this); 
    tv1.setText("HELLO"); 
    ll.addView(tv1); 

    TextView tv2 = new TextView(this); 
    tv2.setText("WORLD"); 
    ll.addView(tv2); 

    setContentView(ll); 
} 

你怎麼做相同的自定義視圖子類中,?有沒有setContentViewonCreate方法...

+0

可能是[這一個](http://stackoverflow.com/questions/14054197/how-to-get-the-name-of-textview-included-in-linear-layout-in-onclicklistener) –

+0

參考這個鏈接http://stackoverflow.com/questions/14081339/how-can-i-declare-textview-as-global-variable-to-use-in-other-class/14081472#14081472 –

回答

28

好吧,我發現這樣做的一種方式。基本上,不需要直接對子類進行子類化,您需要繼承通常在XML中定義的最頂級類。例如,如果您的自定義視圖需要LinearLayout作爲其最頂級的類,那麼您的自定義視圖應該只是子類LinearLayout。

例如:

public class MyCustomView extends LinearLayout 
{ 
    public MyCustomView(Context context, AttributeSet attrs) 
    { 
     super(context, attrs); 

     setOrientation(LinearLayout.VERTICAL); 
     setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); 

     TextView tv1 = new TextView(context); 
     tv1.setText("HELLO"); 
     addView(tv1); 

     TextView tv2 = new TextView(context); 
     tv2.setText("WORLD"); 
     addView(tv2); 
    } 
} 

是繼承的LinearLayout一個 「黑客」?不是我所能看到的。一些官方的View子類也是這樣做的,比如NumberPickerSearchView(儘管它們從XML中擴充了它們的佈局)。

經過反思,這實際上是一個非常明顯的答案。

+1

超級回答,謝謝! ! –

+1

很有意思 –

0

如果我理解你的問題,你需要使用充氣,就像這樣:

public final class ViewHolder { 
     public TextView title; 
     public TextView artist; 
     public TextView duration; 
     public ImageView thumb_image; 
    //A class for the ViewHolder 

    } 

// Put this where you want to inflate this layout, could be a customlistview 
View view = getLayoutInflater().inflate(R.layout.your_layout, null); 
holder = new ViewHolder(); 
    holder.title = (TextView)view.findViewById(R.id.title); // title 
    holder.artist = (TextView)view.findViewById(R.id.artist); // artist name 
    holder.duration = (TextView)view.findViewById(R.id.duration); // duration 
    holder.thumb_image=(ImageView)view.findViewById(R.id.list_image); // thumb image 
相關問題