我們正在開發一個Android應用程序,我們希望在顯示View時重新佈局UI。 因爲我們無法計算XML文件中按鈕的高度,所以我們要計算它並顯示它拋出我們的Java代碼。 但是我們的方法fit()在從onCreate調用時不起作用,而當它從我們的Action溢出中調用時它就起作用。 我們在Android模擬器和三星Galaxy SIII上試過這段代碼。 任何人都可以幫助我們嗎? 感謝Fotoschnitzel未調用其他方法onCreate
下面的代碼:
public class Game extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.classic);
fit();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.potz1000, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.settings:
fit();
default:
return super.onOptionsItemSelected(item);
}
}
public void fit() {
Button Button1=(Button)findViewById(R.id.grid1);
Button Button2=(Button)findViewById(R.id.grid2);
Button Button3=(Button)findViewById(R.id.grid3);
Button Button4=(Button)findViewById(R.id.grid4);
Button Button5=(Button)findViewById(R.id.grid5);
Button Button6=(Button)findViewById(R.id.grid6);
Button Button7=(Button)findViewById(R.id.grid7);
Button Button8=(Button)findViewById(R.id.grid8);
Button Button9=(Button)findViewById(R.id.grid9);
LinearLayout Lin1=(LinearLayout)findViewById(R.id.lin1);
LinearLayout Lin2=(LinearLayout)findViewById(R.id.lin2);
LinearLayout Lin3=(LinearLayout)findViewById(R.id.lin3);
LinearLayout Global=(LinearLayout)findViewById(R.id.LinearLayout1);
LinearLayout Up=(LinearLayout)findViewById(R.id.bestfiller);
ProgressBar Bar=(ProgressBar)findViewById(R.id.progressBar1);
int x = Button1.getWidth();
int y = Global.getHeight();
int z = Bar.getHeight();
int Filler=y-3*x-z;
if (Filler > 50){
Up.setLayoutParams(new LinearLayout.LayoutParams(3*x, Filler));
Lin1.setLayoutParams(new LinearLayout.LayoutParams(3*x, x));
Lin2.setLayoutParams(new LinearLayout.LayoutParams(3*x, x));
Lin3.setLayoutParams(new LinearLayout.LayoutParams(3*x, x));}
double size= x*0.4;
Button1.setTextSize((float)size);
Button2.setTextSize((float)size);
Button3.setTextSize((float)size);
Button4.setTextSize((float)size);
Button5.setTextSize((float)size);
Button6.setTextSize((float)size);
Button7.setTextSize((float)size);
Button8.setTextSize((float)size);
Button9.setTextSize((float)size);
}
}
看到http://stackoverflow.com/questions/6145001/getwidth-and-getheight-are-returning-a-zero或http://stackoverflow.com/questions/18268915/views-getwidth-and -getheight-返回-0 –