2012-07-14 107 views
2

嗨我想加載一個按鈕到一個視圖尋呼機,我有它加載,但它目前正在填充整個屏幕我想它它包裝內容到其確切的大小,然後放置它在屏幕中間。我試圖設置按鈕的layoutparams,但是當我運行應用程序它仍然填充父項。有誰知道如何以編程方式設置按鈕的佈局和位置?Android以編程方式設置按鈕佈局

繼承人什麼我都試過到目前爲止

@Override 
     public Object instantiateItem(View collection, int position) { 

      RelativeLayout.LayoutParams rel_btn = new RelativeLayout.LayoutParams(
      LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); 
      rel_btn.addRule(RelativeLayout.CENTER_VERTICAL); 
      rel_btn.addRule(RelativeLayout.CENTER_HORIZONTAL); 
      rel_btn.height = 60; 
      rel_btn.width = 60; 
      Button tv = new Button(cxt); 
      tv.setLayoutParams(rel_btn); 
      tv.setText("League " + (position+1)); 
      tv.setTextColor(Color.WHITE); 
      tv.setTextSize(30); 
      tv.setBackgroundDrawable(getResources().getDrawable(R.drawable.ls_level_eng1)); 

      ((ViewPager) collection).addView(tv,0); 

      return tv; 
     } 

回答

1

有你通過代碼這樣做什麼特別的原因?你可以簡單地膨脹一個佈局,並使用佈局編輯器來幫助你調整你的Button。這樣你就不會那麼猜測了。

public Object instantiateItem(View collection, int position) { 

final LayoutInflater mLayoutInflater = (LayoutInflater) collection.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); 

final View view = inflater.inflate(R.layout.your_layout, null); 

((ViewPager) collection).addView(view, 0); 

return view; 

在這種情況下,您需要這樣做。我在代碼中添加了註釋。

public Object instantiateItem(View collection, int position) { 

    // Create your LayoutParams 
    final RelativeLayout.LayoutParams rel_btn = new RelativeLayout.LayoutParams(
      RelativeLayout.LayoutParams.WRAP_CONTENT, 
      RelativeLayout.LayoutParams.WRAP_CONTENT); 

    // Add your rules 
    rel_btn.addRule(RelativeLayout.CENTER_VERTICAL); 
    rel_btn.addRule(RelativeLayout.CENTER_HORIZONTAL); 

    // And anything extra 
    rel_btn.height = 60; 
    rel_btn.width = 60; 

    // Create a new RelativeLayout for your RelativeLayout.LayoutParams 
    RelativeLayout relativeLayout = new RelativeLayout(MainActivity.this); 

    // Give your RelativeLayout LayoutParams 
    relativeLayout.setLayoutParams(rel_btn); 

    // Create your Button 
    Button tv = new Button(MainActivity.this); 
    tv.setText("League " + (position + 1)); 
    tv.setTextColor(Color.WHITE); 
    tv.setTextSize(30); 
    tv.setLayoutParams(rel_btn); 
    // You don't need to use setBackgroundDrawable if you're only 
    // grabbing a Resource 
    tv.setBackgroundResource(R.drawable.ls_level_eng1); 

    // Add your Button to your RelativeLayout 
    relativeLayout.addView(tv); 

    // Return your RelativeLayout 
    ((ViewPager)collection).addView(relativeLayout, 0); 
    return relativeLayout; 
} 
+0

是的,因爲按鈕將變成動態的,所以它的源將從數組中拉出我現在只用一個 – 2012-07-14 14:47:03

相關問題