Android: Set ImageView layout_height programmatically

后端 未结 2 1123
萌比男神i
萌比男神i 2020-12-24 07:38

I have an ImageView in my main.xml file:



        
相关标签:
2条回答
  • 2020-12-24 08:05

    You can do something like this:

    LinearLayout.LayoutParams layoutParams  = new LinearLayout.LayoutParams(width_physical_pixels, height_physical_pixels);
    imageView.setLayoutParams(layoutParams);
    

    But in the parameters it takes a pixel, so you would have to use the formula to convert pixels to dp, for example you can use this to convert:

    float scale = getBaseContext().getResources().getDisplayMetrics().density;    
    px = dp_that_you_want * (scale / 160);
    

    Putting everything together:

    //Get screen density to use in the formula.
    float scale = getBaseContext().getResources().getDisplayMetrics().density;    
    px = dp_that_you_want * (scale / 160);
    
    LinearLayout.LayoutParams layoutParams  = new LinearLayout.LayoutParams(px, px);
    imageView.setLayoutParams(layoutParams);
    

    I don't know if this is what you are looking for, or if it will work, so let me know if it does.

    0 讨论(0)
  • 2020-12-24 08:14

    I think you want something like this:

    ImageView imgView = (ImageView) findViewById(R.id.pageImage);
    imgView.getLayoutParams().height = 200;
    

    So first we get the ImageView from the XML. Then getLayoutParams() gets you exactly the params you may edit then. You can set them directly there. The same for the width etc.

    About the unit (sp,dp...) I found something here. Hope this helps:

    Use DIP, SP metrics programmatically

    There they mention, that all units are pixels. In the example he sets the minimum width of 20sp like this:

    TextView tv0 = new TextView(this);
    int px = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 20, getResources().getDisplayMetrics());
    tv0.setMinimumWidth(px);
    

    P.S. Here is the complete code I use. Hopefully this is what you want:

    package com.example.testproject2;
    
    import android.os.Bundle;
    import android.app.Activity;
    import android.view.Menu;
    import android.widget.ImageView;
    
    public class MainActivity extends Activity {
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            ImageView imgView = (ImageView) findViewById(R.id.pageImage);
            imgView.getLayoutParams().height = 500;
        }
    
        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            getMenuInflater().inflate(R.menu.activity_main, menu);
            return true;
        }
    }
    
    0 讨论(0)
提交回复
热议问题