繁体   English   中英

无法从MainActivity.java创建布局

[英]Unable to create layout from MainActivity.java

我正在尝试从MainActivity.java创建布局,但我的模拟器未显示我从MainActivity.java创建的布局和按钮。 我是否需要更改activity_main.xml中的某些内容? 这是代码,

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

我没有测试您的代码,但是我想这是因为您没有为布局添加一些LayoutParams ,例如,布局的宽度和高度。 如果您不想使用固定的宽度和高度,则可以使用LayoutParams.WRAP_CONTNTMATCH_PARENT

我想您应该在@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的按钮。

希望这可以帮助 !

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM