Activity is not showing button

Asked

Viewed 24 times

0

I’m trying to create a button by code, but it just doesn’t show up. This isn’t the main activity, just for the record.

   package com.example.conjuradortormenta;

import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;

public class ListadePersonagens extends AppCompatActivity implements View.OnClickListener{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_listade_personagens);

        LinearLayout layout = new LinearLayout(this);
        layout.setOrientation(LinearLayout.VERTICAL);

        Button botão = new Button(this);// cria o botão "criar novo"
        botão.setText("Criar Novo");
        botão.setId(0);

        botão.setOnClickListener(this);
    }


@Override
public void onClick(View view)
{
    int id=view.getId(), num;
    SharedPreferences shared=getSharedPreferences("com.example.conjuradortormenta_informaçoes_de_personagem", MODE_PRIVATE);
    num=shared.getInt("numero_de_personagens", -1);
    if(id>0 && id<num)
    {
        Intent nova= new Intent(this, teste.class);
        startActivity(nova);
    }
    else if(id==0)
    {
        Intent nova = new Intent (this, CriadordePersonagem.class);
        startActivity(nova);
    }
}

}

1 answer

1


Hello, Cicero!

You need to add the button to the layout. Try this

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_listade_personagens);

    LinearLayout layout = new LinearLayout(this);
    layout.setOrientation(LinearLayout.VERTICAL);

    Button botao = new Button(this);// cria o botão "criar novo"

    // Isso definirá as dimensões do botão
    botao.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); 
    botao.setText("Criar Novo");
    botao.setId(0);
    botao.setOnClickListener(this);

    layout.addView(botao);  // Faltou isso
}

Try not to use accents when naming variables. I hope this helps!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.