【问题标题】:EditText on different devices or emulator is in a deferent position不同设备或模拟器上的 EditText 处于不同的位置
【发布时间】:2015-12-30 00:46:09
【问题描述】:

我将下面的代码用于弹出警报框,其中包含EditText。我正在使用边距来对齐下面代码中的EditText。问题是我用于一个设备或模拟器的边距数字将在其他设备或模拟器上关闭。如果我正确对齐一个设备,它会在另一台设备上看起来关闭。任何帮助表示赞赏。

AlertDialog.Builder aBuilder = new      AlertDialog.Builder(ExpenseSheet.this);
    LinearLayout layout = new LinearLayout(this);
    layout.setOrientation(LinearLayout.VERTICAL);
    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
    params.setMargins(85, 0, 50, 0);
    // Set up the input
    final EditText input = new EditText(ExpenseSheet.this);
    //FOCUSING ON POPUP WINDOW TEXT
    input.requestFocus();
    layout.addView(input, params);

    // Specify the type of input expected; this, for example, sets the input as a password, and will mask the text
    input.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
    //limiting the amount of characters
    input.setFilters(new InputFilter[]{new InputFilter.LengthFilter(8)});
    aBuilder.setView(layout);

【问题讨论】:

    标签: android android-edittext alignment


    【解决方案1】:

    问题是您使用硬编码数字作为默认表示像素的边距。根据设备的屏幕密度,此像素数可以在设备上转换为更长或更短的实际长度。

    您应该尝试将这些值与屏幕密度相乘,以使它们在不同屏幕密度的设备上看起来保持不变。

    示例:

     final DisplayMetrics metrics = context.getResources().getDisplayMetrics();
     final float screenDensity = metrics.density;
     double mWidth = 25 * screenDensity;// constant width across densities
     double mHeight = 30 * screenDensity;// constant height across densities
    

    现在您可以使用这些变量而不是硬编码的值来获得跨各种屏幕密度的统一效果。

    【讨论】:

    • 我粘贴了你的代码并且上下文是红色的。上下文存在编译器错误。
    • 在您的情况下 context 将被替换为 ExpenseSheet.this ,因为这是您的活动和轮流上下文。我建议您阅读有关上下文的更多信息。
    • 太棒了!非常感谢。我只是好奇,你们帮助人们真正得到了什么样的激励?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-09
    • 2011-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-01
    相关资源
    最近更新 更多