2015-01-10 26 views
0

我試圖從MainActivity.java創建佈局,但我的模擬器沒有顯示佈局和從MainActivity.java創建的按鈕。我必須改變activity_main.xml中的內容嗎? 下面是代碼,無法從MainActivity.java創建佈局

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); 
    } 
} 

回答

0

我沒有測試你的代碼,但我想那是因爲你沒有添加一些LayoutParams爲你的佈局,例如,你的佈局的寬度和高度。如果您不想使用固定的寬度和高度,則可以使用LayoutParams.WRAP_CONTNTMATCH_PARENT代替。

0

我想你應該在@Override之前創建Button

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); 
    } 

您還沒有指定button的尺寸。因此,它創建了一個按鈕0dp x 0dp

希望這會有所幫助!

+0

它沒有工作 –