2016-10-25 20 views
0

添加我有一個觀點看起來像這樣 -Android的自定義按鈕(XML)通過代碼

<View 
      android:layout_width="match_parent" 
      android:layout_height="@dimen/line" 
      android:background="#000000"></View> 

     <Button 
      android:id="@+id/button13" 
      android:layout_width="match_parent" 
      android:layout_height="@dimen/button_height" 
      android:background="@drawable/border" 
      android:drawableLeft="@mipmap/ic_launcher" 
      android:text="Button" /> 

我想用JAVA代碼,將其添加到我的活動。 我試圖做手工

LinearLayout layout = (LinearLayout) findViewById(R.id.layout); 
    Button btn = new Button(this); 
    btn.setText("hello"); 

    int size = (int)getResources().getDimension(R.dimen.button_height); 

    View line = new View(this); 
    LinearLayout.LayoutParams lparams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,(int)getResources().getDimension(R.dimen.line)); 
    line.setLayoutParams(lparams); 
    line.setBackgroundColor(Color.BLACK); 
    layout.addView(line); 


    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, size); 
    btn.setLayoutParams(params); 
    btn.setBackground(getResources().getDrawable(R.drawable.border)); 
    layout.addView(btn); 

,但我不能進入0.1dp值作爲該行的高度。我該如何將xml代碼添加到java上的活動?

+0

檢查此問題http://stackoverflow.com/questions/4605527/converting-pixels-to-dp – Farid

回答

0

請試試這個。

linearLayout = (LinearLayout) findViewById(R.id.ll_parent); 
     Button btn = new Button(this); 
     btn.setText("hello"); 

     View line = new View(this); 
     LinearLayout.LayoutParams lparams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,10); 
     line.setLayoutParams(lparams); 
     line.setBackgroundColor(Color.BLACK); 
     linearLayout.addView(line); 


     LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 120); 
     btn.setLayoutParams(params); 

     btn.setBackgroundColor(Color.GRAY); 
     linearLayout.addView(btn);