如何在外部Java类中添加动态按钮?

时间:2018-10-20 09:02:41

标签: java android android-studio button android-button

我在另一个Java类中创建public void onCreate(Bundle SavedInstanceState)时遇到问题。因此,我无法在Java中创建动态按钮。我不知道该怎么做。 这是我的Java课

public class GamePanel extends SurfaceView implements SurfaceHolder.Callback
{
    public static final int WIDTH = 856;
    public static final int HEIGHT = 480;
    public static final int MOVESPEED = -5;
    private long smokeStartTime;
    private long missileStartTime;
    private MainThread thread;
    private Background bg;
    private Player player;
    private ArrayList<Smokepuff> smoke;
    private ArrayList<Missile> missiles;
    private ArrayList<TopBorder> topborder;
    private ArrayList<BotBorder> botborder;
    private Random rand = new Random();
    private int maxBorderHeight;
    private int minBorderHeight;
    private boolean topDown = true;
    private boolean botDown = true;
    private boolean newGameCreated;

    public void onCreate(Bundle SavedInstanceState) {
        super.onCreate(SavedInstanceState);
    }

这是我的主要Java,具有该java类的contentView。.

public class Game extends Activity {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //turn title off
        requestWindowFeature(Window.FEATURE_NO_TITLE);

        //set to full screen
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setContentView(new GamePanel(this));

    }

请帮助我找到解决方案,并在GamePanel Java类中创建一个动态按钮。

1 个答案:

答案 0 :(得分:0)

 //in your activity add this for button
    LinearLayout layout = (LinearLayout) findViewById(R.id.linear_layout_tags);

    //set the properties for button
    Button btnTag = new Button(this);
    btnTag.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
    btnTag.setText("Button");
    btnTag.setId(some_random_id);

    //add button to the layout
    layout.addView(btnTag);