Mehran Mehran - 5 months ago 26
Android Question

making android views in runtime

I'm importing a windows pairs game (writen in java) to android
but when I run this I can see no buttons...
(currently my code does not seems nice cuz I shoud deliver it to uni fast)

what is going wrong here?

package mgh;

import mgh.mgh.R;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsoluteLayout;
import android.widget.Button;
import android.widget.RelativeLayout;

public class mghActivity extends Activity implements OnClickListener {



protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new mghActivity();
}



public int numberOfClickes=0;
public card continueCard=null;
public int killedCards=0;
public card selectedCard=null;
public long spentTime=0;
public card[][] card=new card[4][4];


public void mghActivity(){

setTitle("pairs");
//setVisible(true);
//setSize(500,500 );
//setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
AbsoluteLayout lay=new AbsoluteLayout(this);

int[] clr=new int[8];
short[] timesUsed=new short[8];
for (int i=0;i<=7;i++)
timesUsed[i]=0;
for (int i=0;i<=7;i++)
clr[i]= Color.rgb(((int)(Math.random()*2))*255,
((int)(Math.random()*2))*255,
((int)(Math.random()*2))*255);
for (int i=0;i<=3;i++)
for (int j=0;j<=3;j++){
int rnd=0;
while (timesUsed[rnd]>=2)
rnd=(int)(Math.random()*8)%8;
timesUsed[rnd]++;
card[i][j]=new card(this,clr[rnd]);

//card[i][j].setEnabled(false);

AbsoluteLayout.LayoutParams mparams=new AbsoluteLayout.LayoutParams
(lay.getWidth()/4,lay.getHeight()/4,(lay.getWidth()/4)*i,(lay.getWidth()/4)*j);
lay.addView(card[i][j],mparams);

card[i][j].setOnClickListener(this);

}
setContentView(lay);



}


public void onClick(View arg0) {


}
}

class card extends Button {///not completed
public int color;
public card(Context context,int color){
super(context);
this.color=color;
setBackgroundColor(color);
}
}

Answer

In method onCreate, you just new mghActivity but did not call the the method mghActivity. And mghActivity is not a constructor. You shall remove the void before mghActivity. Then it will be a constructor and called automatically. Even so, I will not recommend creating an Activity like this.