简体   繁体   English

在Android中以编程方式设置布局的大小

[英]set size of layout programmatically in android

I want to create a layout depend on size of device screen. 我想根据设备屏幕的大小来创建布局。 This is my MainActivity 这是我的MainActivity

public class LoginActivity extends Activity {

int width_device;
int height_device;
LinearLayout layout_login_content;
LinearLayout.LayoutParams param;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    // Get screen size
    width_device = Utility.getDeviceWidth(this);
    height_device = Utility.getDeviceHeight(this);

    // Get widget from layout
    layout_login_content = (LinearLayout) findViewById(R.id.layout_login_content);

    // Set up layout size
    param = (LinearLayout.LayoutParams) layout_login_content
            .getLayoutParams();
    param.width = width_device * 60 / 100;
    param.height = height_device * 60 / 100;
    layout_login_content.setLayoutParams(param);
}

Don't worry about how to get screen size. 不用担心如何获得屏幕尺寸。 I did it and it worked. 我做到了,它奏效了。

This is my main_fragment.xml 这是我的main_fragment.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/layout_login_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:orientation="vertical"
tools:context="login.LoginActivity" >
</LinearLayout>

And this is error message 这是错误消息

java.lang.ClassCastException: android.widget.FrameLayout$LayoutParams cannot be cast to android.widget.LinearLayout$LayoutParams

I dont know what happen here. 我不知道这里会发生什么。 I declare LinearLayout.LayoutParams , get params from LinearLayout in xml. 我宣布LinearLayout.LayoutParams ,从获得PARAMS LinearLayout XML格式。 But why it can't cast correctly? 但是为什么它不能正确投射?

Sorry about my english. 对不起,我的英语。 I hope everyone know what I mean :( Thank you so much! 希望每个人都明白我的意思:(非常感谢!

Looks like your LinearLayout is inheriting some FrameLayout params. 看起来您的LinearLayout继承了一些FrameLayout参数。

Try simply using FrameLayout.LayoutParams instead of LinearLayout.LayoutParams : 尝试简单地使用FrameLayout.LayoutParams而不是LinearLayout.LayoutParams

param = (FrameLayout.LayoutParams) layout_login_content.getLayoutParams();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM