问题
I can not decide for himself the task will be to ask
I want to measure the height of the ListView. Can not catch the moment of rendering ListView (rssListView.getHight(); = 0 )
public class RSSactivity extends Activity {
public static RssItem selectedRssItem = null;
String feedUrl = "";
ListView rssListView = null;
ArrayList<RssItem> rssItems = new ArrayList<RssItem>();
ArrayAdapter<RssItem> aa = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
rssListView = (ListView) findViewById(R.id.rssListView);
aa = new ArrayAdapter<RssItem>(this, R.layout.list_item, rssItems);
rssListView.setAdapter(aa);
feedUrl = rssURLTV.getText().toString();
refressRssList();
rssListView.getWidth(); // = 0 ,
}
private void refressRssList() {
ArrayList<RssItem> newItems = RssItem.getRssItems(feedUrl);
rssItems.clear();
rssItems.addAll(newItems);
aa.notifyDataSetChanged();
}
}
target to calculate the number of items intermeddle ListView screen
回答1:
In onCreate:
rssListView.getViewTreeObserver().addOnGlobalLayoutListener(
new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
// If you need this to be called again, then run again addOnGlobalLayoutListener.
mainPanel.getViewTreeObserver().removeGlobalOnLayoutListener(this);
rssListView.getWidth(); // It's available here.
}
});
回答2:
why you need Listview's Height()? if u want to check empty Listview then you can do using setEmptyListview().
回答3:
You can Measure the height of listview by using size method.
rssItems.size();
Hope it helps you.
回答4:
When onCreate method is called the screen is not loaded so every layout component has height = 0 and width = 0. If you want to know the height or width do it before the screen is loaded. The way I use is make a thread that starts running on onCreate. The thread asks for layout object height, while it is 0 I know that the screen components are not loaded yet. When the height is greater than 0 I commit to UI thread the task I want to do.
Edit: Try to do get the height inside onStart method, but I'm not sure about the screen is loaded yet.
Some Code example:
public void onCreate(Bundle savedBundle){
super.onCreate(savedBundle);
setContentView(R.layout.main);
final ListView lv = (ListView) findViewById(R.id.my_list_view);
Thread thr = new Thread(new Runnable(){
public void run(){
while(lv.getHieght() <= 0){
try{
Thread.sleep(10);
} catch(Exception e) {
}
} //while ends
final int height = lv.getHight();
MyActivity.this.runOnUiThread(new Runnable(){
public void run(){
myMethod(height);
} //UI thread runnable-run method ends
}); //UI Runnable declaration ends
} //thread runnable-run method ends
}); //Thread Runnable declaration ends
thr.start();
} // onCreate ends.
public void myMethod(int height){
//opeate with valid height
}
来源:https://stackoverflow.com/questions/11795862/i-want-to-measure-the-height-of-the-listview-gethight-0