2017-08-15 104 views
0

The current popupAndroid首次ImageView的拉伸

我創建上述彈出,該專利的內容包括一個主垂直的LinearLayout內水平的LinearLayout圖的行。每個水平LinearLayout都包含一個ImageView和一個TextView。 我在一個PopupWindow中創建這個,並以編程方式這樣做,以便我可以根據需要更改ImageView源代碼。

正如你所看到的第一個圖標似乎佔用了大量的空間,儘管有相同的代碼生成它的其他圖標。

下面是代碼:

LinearLayout verticalLayout = new LinearLayout(context); 
     verticalLayout.setOrientation(LinearLayout.VERTICAL); 
LinearLayout.LayoutParams mainLayoutParams = 
       new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); 
verticalLayout.setLayoutParams(mainLayoutParams); 

LinearLayout.LayoutParams layoutParams = 
       new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); 
LinearLayout.LayoutParams iconParams = 
       new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT); 
LinearLayout.LayoutParams textParams = 
       new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); 

//History row 
LinearLayout historyLayout = new LinearLayout(context); 
historyLayout.setLayoutParams(layoutParams); 
historyLayout.setOrientation(LinearLayout.HORIZONTAL); 
ImageView historyIcon = new ImageView(context); 
historyIcon.setImageResource(R.drawable.small_book_grey); 
historyIcon.setAdjustViewBounds(true); 
historyIcon.setLayoutParams(iconParams); 
historyLayout.addView(historyIcon); 
TextView historyText = new TextView(context); 
historyText.setLayoutParams(textParams); 
historyText.setText("History"); 
historyLayout.addView(historyText); 
verticalLayout.addView(historyLayout); 

//Exam row... 
//... (duplicate of history row) 

我已經試過玩弄佈局參數,甚至創建一個顯示內容,因爲我想一個模擬的XML佈局,以匹配參數。 如果任何人都可以提供一些建議,使其與其他人一樣大小的圖書圖標,我會很感激。

+0

您應該使用listview並創建適配器來填充所有這些文本和圖像。不需要以編程方式創建多個佈局 – AndroidGeek

+0

我希望能夠選擇不同的圖像作爲圖標,哪些(告訴我是否我錯了)我不認爲可以使用listview來完成。最終我想將這個彈出菜單變成一個彈出菜單,如果這有助於理解我在做什麼。 –

+0

您可以在運行時在列表視圖中輕鬆更改圖像。 – AndroidGeek

回答

0

添加scaleType到fitCenter

+0

這並沒有改變任何東西 –

0

寫代碼的ImageView下historyIcon.setAdjustViewBounds(true);

historyIcon.setWidth()` 

,並根據您的佈局把寬度。

+0

對不起,我不確定你的意思對我來說意味着什麼 –

0

雖然我沒有弄清楚爲什麼第一張圖片的縮放比例與其他圖片不同,但我確實找到了另一種解決方案:使用複合左邊的繪圖。

 historyText.getViewTreeObserver() 
       .addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { 
        @Override 
        public void onGlobalLayout() { 
         Drawable img = m_context.getResources().getDrawable(
           R.drawable.small_book_grey); 
         img.setBounds(0, 0, img.getIntrinsicWidth() * historyText.getMeasuredHeight()/img.getIntrinsicHeight(), historyText.getMeasuredHeight()); 
         historyText.setCompoundDrawables(img, null, null, null); 
         historyText.getViewTreeObserver().removeOnGlobalLayoutListener(this); 
        } 
       }); 

手動設置邊界以匹配TextView的工作。看起來笨重,但這是我能做到我所追求的唯一方法。

+0

這可能是由於本書的圖像大。 –