I m trying to create a layout from MainActivity.java but my emulator is not showing the layout and the button which i have created from MainActivity.java. Do i have to change something in activity_main.xml? Here is the code,
package com.example.pratt.myapplication;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.util.Log;
import android.widget.RelativeLayout;
import android.widget.Button;
import android.graphics.Color;
public class MainActivity extends ActionBarActivity {
private static final String TAG="My Message";
@Override
protected void onCreate(Bundle savedInstanceState) {
/*
*/
super.onCreate(savedInstanceState);
RelativeLayout myLayout=new RelativeLayout(this);
Button blue_button=new Button(this);
myLayout.setBackgroundColor(Color.RED);
myLayout.addView(blue_button);
blue_button.setText("Blue Button");
Log.i(TAG,"onCreate");
setContentView(myLayout);
}
@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);
}
}
I didn't test your code, but I guess it's because you didn't to add some LayoutParams
for your layout, for example, your layout's width and height. If you don't want to use fixed width and height you can use LayoutParams.WRAP_CONTNT
or MATCH_PARENT
instead.
I suppose you should create the Button
before @Override
.
private static final String TAG="My Message";
@Override
protected void onCreate(Bundle savedInstanceState) {
/*
*/
super.onCreate(savedInstanceState);
RelativeLayout myLayout=new RelativeLayout(this);
myLayout.setBackgroundColor(Color.RED);
Button blue_button=new Button(this);
blue_button.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT)
myLayout.addView(blue_button);
blue_button.setText("Blue Button");
Log.i(TAG,"onCreate");
setContentView(myLayout);
}
You have not specified the dimensions of the button
. Hence, it creates a button of 0dp x 0dp
.
Hope this helps !
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.