2016-12-29 37 views
0

我正在使用具有長項目和短項目的AppCompatSpinner控件。選擇一個短項目時,微調框太寬,它的圖標顯示得太離文本太遠,因爲文本太短。如果物品很小,是否有辦法讓旋轉器變小?將微調器寬度調整爲選定項目

+0

做你試圖使用'spinner.setDropDownWidth(寬); '? –

+0

我需要'寬度'是動態的 – Ruben2112

回答

0

這是相當hacky壽。

spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { 
     @Override public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) { 
     String text = adapterView.getItemAtPosition(position).toString(); 
     Rect bounds = new Rect(); 
     Paint textPaint = new Paint(); 
     textPaint.measureText(text); 
     textPaint.setTextSize(45); 
     textPaint.getTextBounds(text, 0, text.length(), bounds); 
     int width = bounds.width(); 
     ViewGroup.LayoutParams params = spinner.getLayoutParams(); 
     params.width = width + 290; 
     spinner.setLayoutParams(params); 
     } 
     @Override public void onNothingSelected(AdapterView<?> adapterView) { 
     } 
    }); 

希望它能幫助:)