Can anyone help me why my button is not in the center

0 punkdue mekaprasit · February 21, 2015
this is my code that I follow Bucky buy when the simulator is run my button is still on top not in the center
I'm new at android 


package com.example.computer.newinterface;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.RelativeLayout;
import android.widget.Button;
import android.graphics.Color;

public class MainActivity extends ActionBarActivity {

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

        //layout
        RelativeLayout LoginLayout = new RelativeLayout(this);
        LoginLayout.setBackgroundColor(Color.GRAY);

        RelativeLayout.LayoutParams buttonDetail = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.WRAP_CONTENT,
                RelativeLayout.LayoutParams.WRAP_CONTENT
        );

        //makeButtonInTheCenter
        buttonDetail.addRule(RelativeLayout.CENTER_HORIZONTAL);
        buttonDetail.addRule(RelativeLayout.CENTER_VERTICAL);

        //Button
        Button LoginButton = new Button(this);
        LoginButton.setText("Log in");
        LoginButton.setBackgroundColor(Color.BLUE);

        LoginLayout.addView(LoginButton);
        setContentView(LoginLayout);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}


}

Post a Reply

Replies

Oldest  Newest  Rating
0 sohrab zia ✓ᵛᵉʳᶦᶠᶦᵉᵈ · February 21, 2015
why you duplicated this line below?

RelativeLayout.LayoutParams.WRAP_CONTENT

add WRAP_CONTENT for horizontal and vertical. watch the tutorial again.
0 T P · February 22, 2015
Hi, You did not added the rule.
Add rule to the button like this:

LoginLayout.addView(LoginButton,buttonDetail);
  • 1

Java / Android Development

106,912 followers
About

Very popular language used to create desktop applications, website applets, and Android apps.

Links
Moderators
Bucky Roberts Administrator