【问题标题】:Change height of android button through code通过代码更改android按钮的高度
【发布时间】:2013-04-09 08:56:52
【问题描述】:

我正在尝试在运行时通过代码更改按钮的高度和宽度。

我的布局 xml

   <Button
    android:id="@+id/button1"
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:layout_alignParentRight="true"
    android:layout_below="@+id/button2"
    android:background="@drawable/button1_background" 
    />

主要活动代码

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
   //some other code
   int displaywidth= getResources().getDisplayMetrics().widthPixels;
    Button f_button = (Button) findViewById(R.id.button1);
    Log.d("F_button width before is",""+ f_button.getWidth());
    f_button.setWidth(displaywidth/2);
    Log.d("F_button width after is",""+ f_button.getWidth());
//some other code
}

Logcat 将宽度前后的 F_button 显示为“0”。

我做错了什么。

谢谢!

【问题讨论】:

标签: java android button runtime


【解决方案1】:

我认为它可能会帮助你..

Button btn = (Button)findViewById(R.id.btn1); 

android.widget.LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,60); // 60 is height you can set it as u need

btn.setLayoutParams(lp);

【讨论】:

    【解决方案2】:

    在java(Activity)中使用下面的代码

      f_button.setLayoutParams (new LayoutParams(50, LayoutParams.WRAP_CONTENT));
    

    【讨论】:

      【解决方案3】:

      你应该使用

      int displaywidth= getResources().getDisplayMetrics().widthPixels;    
      ViewGroup.LayoutParams buttonlp= (ViewGroup.LayoutParams)f_button.getLayoutParams();
      LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(displaywidth, buttonlp.height);
      buttonlp.setLayoutParams(params);
      

      如果不是LinearLayout,您应该使用按钮的父布局而不是LinearLayout

      【讨论】:

        【解决方案4】:

        是的,我尝试了很长时间来解决这个问题。 Ajay 的解决方案让我成功了。 对于 Kotlin 程序员来说,它看起来像这样:

        btn.layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, 60)
        

        【讨论】:

          猜你喜欢
          • 2017-01-19
          • 1970-01-01
          • 2014-11-17
          • 2015-08-23
          • 1970-01-01
          • 2017-08-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多