Android - 如何将DP转换为PX - 密度独立于绝对像素

时间:2014-05-23 10:39:44

标签: android android-layout android-view android-xml android-viewgroup

我有一种情况需要在运行时添加布局,如下所示:

1。已在XML中定义Button布局:

Button layout in XML

2。当用户点击Button时,EditText和另一个Button会动态添加到现有布局中:

EditText & another Button added dynamically

它在Gingerbread(Android 2.3.5)上正常工作:

G Layout 1 G Layout 2

并不适用于Kitkat(Android 4.4.2):

K Layout 1 K Layout 2

是否有人知道此问题的解决方法?这是我用过的代码:

public class MainActivity extends Activity {

private boolean comment = true;

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

    Button button = (Button)findViewById(R.id.commentbutton);
    button.setOnClickListener(new OnClickListener(){
        @Override
        public void onClick(View v){
            if(comment == true){
                comment = false;
                LinearLayout l = (LinearLayout)findViewById(R.id.comment_layout);
                l.setOrientation(LinearLayout.VERTICAL);

                final EditText e = new EditText(v.getContext());
                e.setId(R.id.commentbox);
                LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(250,100);
                lp.setMargins(0, 20, 0, 0);
                e.setLayoutParams(lp);
                e.setSingleLine(true);
                e.setImeOptions(EditorInfo.IME_ACTION_DONE);
                l.addView(e);

                final Button b = new Button(v.getContext());
                b.setId(R.id.submitbutton);
                lp = new LinearLayout.LayoutParams(150,33);
                lp.setMargins(0, 20, 0, 0);
                b.setLayoutParams(lp);
                b.setText("Submit");
                b.setTextColor(Color.BLACK);
                b.setTypeface(null, Typeface.BOLD);
                b.setBackgroundColor(Color.parseColor("#CCCCCC"));
                b.setFocusable(true);
                b.setFocusableInTouchMode(true);
                l.addView(b);

                e.setOnEditorActionListener(new OnEditorActionListener() {
                    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                        if (actionId == EditorInfo.IME_ACTION_DONE) {
                            b.performClick();
                            return true;
                        }
                        return false;
                    }
                });

                LinearLayout ll = new LinearLayout(v.getContext());
                ll.setId(R.id.productbottomlayout);
                lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,25);
                ll.setLayoutParams(lp);
                ll.setFocusable(true);
                ll.setFocusableInTouchMode(true);
                l.addView(ll);
                ll.requestFocus();

                b.setOnClickListener(new OnClickListener(){
                    @Override
                    public void onClick(View v){
                        LinearLayout l = (LinearLayout) findViewById(R.id.comment_layout);
                        EditText e = (EditText) findViewById(R.id.commentbox);
                        l.removeView(e);
                        Button b = (Button) findViewById(R.id.submitbutton);
                        l.removeView(b);
                        LinearLayout ll = (LinearLayout) findViewById(R.id.productbottomlayout);
                        l.removeView(ll);
                        MainActivity.this.comment = true;
                    }
                });
            }
        }
    });
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

}

这是XML布局:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

<LinearLayout 
            android:id="@+id/comment_layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:layout_marginBottom="25dp"
            android:layout_gravity="center"
            android:gravity="center">

            <Button 
                android:id="@+id/commentbutton"
                android:layout_width="150dp"
                android:layout_height="30dp"
                android:text="Add Comment"
                android:textColor="#000000"
                android:textStyle="bold"
                android:background="#CCCCCC"
                android:onClick="showCommentBox"/>

        </LinearLayout>

</RelativeLayout>

此外,当我们以编程方式添加布局时,我们需要为每个布局元素手动设置ID。

我做到了。他们在这里:

<resources>
    <item  type = "id" name = "commentbox"></item>
    <item  type = "id" name = "submitbutton"></item>
    <item type="id" name="productbottomlayout"></item>
</resources>

3 个答案:

答案 0 :(得分:1)

问题是您是在像素测量单位中设置尺寸。 使用DP或LayoutParams.WRAP_CONTENT可使您的应用程序具有可扩展性和响应性。

那么,那就是我如何设置layoutParams:

lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT);

答案 1 :(得分:0)

添加此方法并使用它将所有像素转换为dpi:

    public static int dpi(int i) {
            Resources r = getResources();
     int value = (int) TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_DIP, i,
            r.getDisplayMetrics());
    return value;
}

来源:https://stackoverflow.com/a/6327095/1977021

答案 2 :(得分:0)

// Try this way,hope this will help you to solve your problem...

Define this method in your class
public int convertSizeToDeviceDependent(int value) {
     DisplayMetrics dm = new DisplayMetrics();
     getWindowManager().getDefaultDisplay().getMetrics(dm);
     return ((dm.densityDpi * value) / 160);
}

Try to replace this line:
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(250,100);

With this:
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(convertSizeToDeviceDependent(250),convertSizeToDeviceDependent(100));

Try to replace this line:
lp = new LinearLayout.LayoutParams(150,33);

With this:
lp = new LinearLayout.LayoutParams(convertSizeToDeviceDependent(150),convertSizeToDeviceDependent(33));

Try to replace this line:
lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,25);

With this:
lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,convertSizeToDeviceDependent(25));