2016-10-25 21 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);