2013-10-24 18 views
0

有一個自定義的相對佈局,並增加了一個按鈕,它我如何相對佈局添加到瀏覽

RelativeLayout rel_layout = new RelativeLayout(mcontext); 
RelativeLayout.LayoutParams rel_param = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FILL_PARENT, RelativeLayout.LayoutParams.FILL_PARENT); 
rel.setLayoutParams(rel_param); 

Button b = new Button(mcontext); 
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); 
b.setLayoutParams(params); 
b.setText("Test"); 
rel_layout.addView(b); 

現在,我想這個相對佈局被添加到一個視圖。我的視圖類看起來這是

public class CustomView extends View { 

Context mcontext; 

public CustomView(Context context) { 
    super(context); 

    this.mcontext = context; 
} 

}

,並在主要活動,我在我的setConentView()

public class MainActivity extends Activity { 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(new CustomView(this)); 
} 

}

調用這個觀點所以現在在屏幕我應該有相應的佈局,其中的按鈕。我不應該使用任何XMl。

我需要在如何創建要添加到我的CustomView類

希望我已經解釋清楚我的問題的動態相對增加的幫助。

+0

添加自定義視圖相對佈局 – Raghunandan

+0

我尋找其他方式輪..我想在CustomView類添加相對佈局 –

回答

0

您的自定義視圖必須擴展ViewGroup而不是View

+0

明顯的,如果你可以用代碼片斷幫助 –

+0

什麼是你自定義視圖應該fo? – pskink

+0

是同意的。我將擴展一個ViewGroup。因爲我想在自定義視圖中放置3個相對佈局,並在我的setContentView() –

0

你不應該那樣做。 RelativeLayoutViewGroupViewGroup是一個View,可以容納一個或多個View作爲孩子。您應該實施自己的ViewGroup而不是View
你可以找到一個教程在這裏實現自定義ViewGroup
https://developer.android.com/reference/android/view/ViewGroup.html

另外,我想建議你實際上可能想直接將RelativeLayoutActivity並沿着放置一些定製部件在它的上面用你提到的按鈕。

0
// try this 
custom_view.xml 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:id="@+id/relCustomView" 
    android:background="@android:color/darker_gray" 
    android:padding="5dp"> 

</RelativeLayout> 

public class CustomView extends View{ 
    private Context context; 

    public CustomView(Context context) { 
     super(context); 
     this.context=context; 
    } 
    public View getCustomView(){ 
     View v = LayoutInflater.from(context).inflate(R.layout.custom_view,null,false); 

     RelativeLayout relCustomView = (RelativeLayout) v.findViewById(R.id.relCustomView); 

     Button b = new Button(context); 
     RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); 
     b.setLayoutParams(params); 
     b.setText("Test"); 
     relCustomView.addView(b); 
     return v; 
    } 
} 

@Override 
public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(new CustomView(this).getCustomView()); 
} 
+0

中使用customView類,這很好,但我有一個限制,我不能使用xml,因爲我必須提供一個.jar文件 –