【问题标题】:How to set layout parameters in Relativelayout using java code如何使用java代码在Relativelayout中设置布局参数
【发布时间】:2012-06-25 18:29:18
【问题描述】:

我已经使用 RelativeLayout 创建了一个布局,但是当方向更改为横向时,我需要更改上边距。

   @Override
  public void onConfigurationChanged(Configuration newConfig) {
   super.onConfigurationChanged(newConfig);

   // Checks the orientation of the screen
   if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {

       RelativeLayout.LayoutParams labelLayoutParams = new RelativeLayout.LayoutParams(
                LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
      // labelLayoutParams.setMargins(0, -100, 0, 0);
       layout.setLayoutParams(labelLayoutParams);

       Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
   } 

但我得到以下异常

 06-25 22:22:31.166: E/AndroidRuntime(8211): java.lang.ClassCastException: android.widget.RelativeLayout$LayoutParams

所以请帮助如何设置布局参数,特别是相对布局的上边距? 程序化

【问题讨论】:

  • 我的建议是添加使用带有Relativelayout前缀的LayoutParams,比如RelativeLayout.LayoutParams.FILL_PARENT。可能 IDE 对 LayoutParams 使用了错误的导入,例如 LinearLayout。
  • RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FILL_PARENT, RelativeLayout.LayoutParams.FILL_PARENT);

标签: java android android-layout android-relativelayout


【解决方案1】:

按照Set the absolute position of a view尝试这种方式

RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FILL_PARENT, RelativeLayout.LayoutParams.FILL_PARENT);

    params.topMargin = 60;

    layout.setLayoutParams(params);

【讨论】:

  • FILL_PARENT 现已弃用,请使用MATCH_PARENT
【解决方案2】:

试试这个:

RelativeLayout.LayoutParams labelLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
labelLayoutParams.topMargin = 10;
layout.setLayoutParams(labelLayoutParams);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-17
    • 2013-06-24
    • 2017-12-31
    • 1970-01-01
    • 2011-07-31
    • 2011-09-21
    • 2013-07-16
    相关资源
    最近更新 更多