2012-06-21 48 views
3

所以,我試圖製作一個動態UI,並且我想爲它添加一個分隔符。不幸的是,我只能找出XML中的一個。是否有可能將此將android UI xml轉換爲代碼

<ImageView 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/seperator" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:paddingBottom="2dp" 
    android:paddingLeft="5dp" 
    android:paddingRight="5dp" 
    android:paddingTop="2dp" 
    android:scaleType="fitXY" 
    android:src="@android:drawable/divider_horizontal_dark" /> 

轉化爲程序代碼?

我最好的嘗試是

ImageView seperator=new ImageView(this); 
seperator.setImageDrawable(drawable.divider_horizontal_dark); 

回答

5

把它放在一個額外的佈局文件和它充氣,當你需要它的代碼 - 我認爲你想做的事,應該是最簡單的方法。

在你的活動:

View v = LayoutInflater.from(this).inflate(R.layout.seperator, null); 

如果充氣佈局:

LinearLayout ll = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.custom_layout, null); 
TextView tv = (TextView) ll.findViewById(R.id.tv); 
+0

哦真的嗎?我能做到嗎?哇。我剛剛花了三個小時重新編寫了一些我已經編入代碼的XML,而且還沒有完成。我認爲你已經爲我節省了很多時間和精力......如果這個搭配合作,我會將你的答案設置爲正確的。乾杯。 – blucalculatr

+0

沒關係,所以,工作。稍微不同的問題:如果我使用佈局inflater的事情爲viewgroup,如linearlayout,有什麼特殊的方式,我應該去編輯一個子TextView中的文本? – blucalculatr

+0

我已編輯我的帖子來涵蓋這個問題:) –

0

您還可以創建一個視圖,定義背景,用的LayoutParams

ViewGroup container = (ViewGroup) findViewById(R.id.container); 
    View separator = new View(context); 
    separator.setBackgroundColor(Color.Black); 
    LayoutParams layoutParams = new LayoutParams(LayoutParams.MATCH_PARENT, 2); 

    container.addView(separator, layoutParams); 
4
添加它

有一個網站可以爲你轉換。您可以設計與eclipse接口,然後提交生成的XML到XMLtoJAVA在線轉換器,它應該爲你做。