Android 运行时布局教程

发布于 2024-08-30 06:26:10 字数 948 浏览 5 评论 0原文

有谁知道如何在 android 运行时执行活动布局或有一个很好的参考?

这是我的活动的代码。我确信我只是忽略了在这里做一些事情:

package com.isi.sa;

import android.app.Activity;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.TextView;

public class SimpleAssessmentTest extends Activity {
  LinearLayout layout;
  TextView question;

  @Override
  public void onCreate(Bundle icicle) {
    super.onCreate(icicle);

    layout = new LinearLayout(this);
    question = new TextView(this);

    layout.setLayoutParams(new ViewGroup.LayoutParams(-1,-1));
    layout.setBackgroundColor(R.color.blue);

    question.setLayoutParams(new ViewGroup.LayoutParams(-1,-2));
    question.setTextColor(R.color.green);
    question.setTextSize(1,14);

    question.setText("This is question1");
    layout.addView(question);

    setContentView(layout);
  }
}

如您所见,我只是尝试添加带有单个文本视图的线性布局(仅用于测试目的)但是,当活动开始时我只是得到一个黑色屏幕上有我的应用程序名称的标题栏。

谢谢

Does anyone know how to perform or have a good reference for doing an activity layout at runtime in android?

Here is the code for my activity. I'm sure I'm just neglecting to do something here:

package com.isi.sa;

import android.app.Activity;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.TextView;

public class SimpleAssessmentTest extends Activity {
  LinearLayout layout;
  TextView question;

  @Override
  public void onCreate(Bundle icicle) {
    super.onCreate(icicle);

    layout = new LinearLayout(this);
    question = new TextView(this);

    layout.setLayoutParams(new ViewGroup.LayoutParams(-1,-1));
    layout.setBackgroundColor(R.color.blue);

    question.setLayoutParams(new ViewGroup.LayoutParams(-1,-2));
    question.setTextColor(R.color.green);
    question.setTextSize(1,14);

    question.setText("This is question1");
    layout.addView(question);

    setContentView(layout);
  }
}

As you can see I'm just trying to add a linear layout with a single text view (just for testing purposes) however, when the activity starts I just get a black screen with a title bar of my app name.

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

红焚 2024-09-06 06:26:10

您忘记设置 contentView。 添加

setContentView(layout);

您应该在 onCreate 方法的末尾

You forgot to set your contentView. You should add

setContentView(layout);

At the end of the onCreate method

滿滿的愛 2024-09-06 06:26:10

您可以查看以下 URL: http://www.linux-mag.com /cache/7705/1.html 。它具有库小部件和自定义小部件。

编辑:

setBackgroundColor 需要以正确的 ARGB 格式输入:0xAARRGGBB。每个 AA、RR、GG 和 BB 的范围是从 00(最小值)到 ff(最大值)。

这里是最低限度的示例,它可以完美地工作。以下是屏幕截图和代码(稍作修改):

http://picturepush.com/public/3313522(旧)

package us.simpleit;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

public class SimpleGUI extends Activity {
    TextView tv;
    EditText et;
    LinearLayout ll;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //LinearLayout ll = new LinearLayout(this);
        ll = new LinearLayout(this);
        ll.setOrientation(android.widget.LinearLayout.VERTICAL);
        ll.setLayoutParams(new ViewGroup.LayoutParams(-1,-1));
        // ARGB: Opaque Red
        ll.setBackgroundColor(0x88ff0000);

        tv = new TextView(this);
        tv.setLayoutParams(new ViewGroup.LayoutParams(-1,-2));
        tv.setText("sample text goes here");
        // ARGB: Opaque Green
        tv.setBackgroundColor(0x5500ff00);
        ll.addView(tv);

        et = new EditText(this);
        et.setLayoutParams(new ViewGroup.LayoutParams(-1,-2));
        et.setText("edit me please");
        // ARGB: Solid Blue
        et.setBackgroundColor(0xff0000ff);
        ll.addView(et);

        Button btn = new Button(this);
        btn.setText("Go!");
        btn.setOnClickListener(new Button.OnClickListener() {
            public void onClick(View v) {
                tv.setText(et.getText().toString());
            }
        });

        ll.addView(btn);
        setContentView(ll);

        //setContentView(R.layout.main);
    }
}

You can check out this URL: http://www.linux-mag.com/cache/7705/1.html . It has both library widgets and custom widgets.

EDIT:

setBackgroundColor requires input in proper ARGB format: 0xAARRGGBB. Each AA, RR, GG and BB range from 00 (minimum) to ff (maximum).

The bare minimum example goes here and it works flawlessly. Here are the screenshot and code (modified a bit):

http://picturepush.com/public/3313522 (old)

package us.simpleit;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

public class SimpleGUI extends Activity {
    TextView tv;
    EditText et;
    LinearLayout ll;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //LinearLayout ll = new LinearLayout(this);
        ll = new LinearLayout(this);
        ll.setOrientation(android.widget.LinearLayout.VERTICAL);
        ll.setLayoutParams(new ViewGroup.LayoutParams(-1,-1));
        // ARGB: Opaque Red
        ll.setBackgroundColor(0x88ff0000);

        tv = new TextView(this);
        tv.setLayoutParams(new ViewGroup.LayoutParams(-1,-2));
        tv.setText("sample text goes here");
        // ARGB: Opaque Green
        tv.setBackgroundColor(0x5500ff00);
        ll.addView(tv);

        et = new EditText(this);
        et.setLayoutParams(new ViewGroup.LayoutParams(-1,-2));
        et.setText("edit me please");
        // ARGB: Solid Blue
        et.setBackgroundColor(0xff0000ff);
        ll.addView(et);

        Button btn = new Button(this);
        btn.setText("Go!");
        btn.setOnClickListener(new Button.OnClickListener() {
            public void onClick(View v) {
                tv.setText(et.getText().toString());
            }
        });

        ll.addView(btn);
        setContentView(ll);

        //setContentView(R.layout.main);
    }
}
想你只要分分秒秒 2024-09-06 06:26:10

下面演示了如何以编程方式创建视图和布局,而不使用布局 xml 文件。它还创建一个圆角矩形布局对象,该对象在放置在其中的任何子对象周围绘制圆角矩形。

package android.example;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
import android.widget.TextView;

public class MessageScreen extends Activity {
 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  int mainBackgroundColor = Color.parseColor("#2E8B57");
  int labelTextColor = Color.parseColor("#FF4500");
  int messageBackgroundColor = Color.parseColor("#3300FF");
  int messageTextColor = Color.parseColor("#FFFF00");

  DisplayMetrics metrics = new DisplayMetrics();
  getWindowManager().getDefaultDisplay().getMetrics(metrics);
  float density = metrics.density;
  int minMarginSize = Math.round(density * 8);
  int paddingSize = minMarginSize * 2;
  int maxMarginSize = minMarginSize * 4;

  TextView label = new TextView(this);
  /*
   * The LayoutParams are instructions to the Layout that will contain the
   * View for laying out the View, so you need to use the LayoutParams of
   * the Layout that will contain the View.
   */
  LinearLayout.LayoutParams labelLayoutParams = new LinearLayout.LayoutParams(
    LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
  label.setLayoutParams(labelLayoutParams);
  label.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
  label.setPadding(paddingSize, paddingSize, paddingSize, paddingSize);
  label.setText(R.string.title);
  label.setTextColor(labelTextColor);

  TextView message = new TextView(this);
  RoundedRectangle.LayoutParams messageLayoutParams = new RoundedRectangle.LayoutParams(
 LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
  /*
   * This is one of the calls must made to force a ViewGroup to call its
   * draw method instead of just calling the draw method of its children.
   * This tells the RoundedRectangle to put some extra space around the
   * View.
   */
  messageLayoutParams.setMargins(minMarginSize, paddingSize,
    minMarginSize, maxMarginSize);
  message.setLayoutParams(messageLayoutParams);
  message.setTextSize(TypedValue.COMPLEX_UNIT_SP, paddingSize);
  message.setText(R.string.message);
  message.setTextColor(messageTextColor);
  message.setBackgroundColor(messageBackgroundColor);

  RoundedRectangle messageContainer = new RoundedRectangle(this);
  LinearLayout.LayoutParams messageContainerLayoutParams = new LinearLayout.LayoutParams(
    LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
  messageContainerLayoutParams.setMargins(paddingSize, 0, paddingSize, 0);
  messageContainer.setLayoutParams(messageContainerLayoutParams);
  messageContainer.setOrientation(LinearLayout.VERTICAL);
  /*
   * This is one of the calls must made to force a ViewGroup to call its
   * draw method instead of just calling the draw method of its children.
   * This tells the RoundedRectangle to color the the exta space that was
   * put around the View as well as the View. This is exterior color of
   * the RoundedRectangle.
   */
  messageContainer.setBackgroundColor(mainBackgroundColor);
  /*
   * This is one of the calls must made to force a ViewGroup to call its
   * draw method instead of just calling the draw method of its children.
   * This is the interior color of the RoundedRectangle. It must be
   * different than the exterior color of the RoundedRectangle or the
   * RoundedRectangle will not call its draw method.
   */
  messageContainer.setInteriorColor(messageBackgroundColor);
  // Add the message to the RoundedRectangle.
  messageContainer.addView(message);

  //
  LinearLayout main = new LinearLayout(this);
  LinearLayout.LayoutParams mainLayoutParams = new LinearLayout.LayoutParams(
    LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
  main.setLayoutParams(mainLayoutParams);
  main.setOrientation(LinearLayout.VERTICAL);
  main.setBackgroundColor(mainBackgroundColor);
  main.addView(label);
  main.addView(messageContainer);

  setContentView(main);
 }
}

RoundedRectangle 布局对象的类定义如下:

/**
 *  A LinearLayout that draws a rounded rectangle around the child View that was added to it.
 */
package android.example;

import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.widget.LinearLayout;

/**
 * A LinearLayout that has rounded corners instead of square corners.
 * 
 * @author Danny Remington
 * 
 * @see LinearLayout
 * 
 */
public class RoundedRectangle extends LinearLayout {
 private int mInteriorColor;

 public RoundedRectangle(Context p_context) {
  super(p_context);
 }

 public RoundedRectangle(Context p_context, AttributeSet attributeSet) {
  super(p_context, attributeSet);
 }

 // Listener for the onDraw event that occurs when the Layout is drawn.
 protected void onDraw(Canvas canvas) {
  Rect rect = new Rect(0, 0, getWidth(), getHeight());
  RectF rectF = new RectF(rect);
  DisplayMetrics metrics = new DisplayMetrics();
  Activity activity = (Activity) getContext();
  activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
  float density = metrics.density;
  int arcSize = Math.round(density * 10);

  Paint paint = new Paint();
  paint.setColor(mInteriorColor);

  canvas.drawRoundRect(rectF, arcSize, arcSize, paint);
 }

 /**
  * Set the background color to use inside the RoundedRectangle.
  * 
  * @param Primitive int - The color inside the rounded rectangle.
  */
 public void setInteriorColor(int interiorColor) {
  mInteriorColor = interiorColor;
 }

 /**
  * Get the background color used inside the RoundedRectangle.
  * 
  * @return Primitive int - The color inside the rounded rectangle.
  */
 public int getInteriorColor() {
  return mInteriorColor;
 }

}

The following demonstrates how to create views and layouts programmatically without using the layout xml files. It also creates a rounded rectangle layout object that draws a rounded rectangle around any child objects that are placed in it.

package android.example;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
import android.widget.TextView;

public class MessageScreen extends Activity {
 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  int mainBackgroundColor = Color.parseColor("#2E8B57");
  int labelTextColor = Color.parseColor("#FF4500");
  int messageBackgroundColor = Color.parseColor("#3300FF");
  int messageTextColor = Color.parseColor("#FFFF00");

  DisplayMetrics metrics = new DisplayMetrics();
  getWindowManager().getDefaultDisplay().getMetrics(metrics);
  float density = metrics.density;
  int minMarginSize = Math.round(density * 8);
  int paddingSize = minMarginSize * 2;
  int maxMarginSize = minMarginSize * 4;

  TextView label = new TextView(this);
  /*
   * The LayoutParams are instructions to the Layout that will contain the
   * View for laying out the View, so you need to use the LayoutParams of
   * the Layout that will contain the View.
   */
  LinearLayout.LayoutParams labelLayoutParams = new LinearLayout.LayoutParams(
    LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
  label.setLayoutParams(labelLayoutParams);
  label.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
  label.setPadding(paddingSize, paddingSize, paddingSize, paddingSize);
  label.setText(R.string.title);
  label.setTextColor(labelTextColor);

  TextView message = new TextView(this);
  RoundedRectangle.LayoutParams messageLayoutParams = new RoundedRectangle.LayoutParams(
 LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
  /*
   * This is one of the calls must made to force a ViewGroup to call its
   * draw method instead of just calling the draw method of its children.
   * This tells the RoundedRectangle to put some extra space around the
   * View.
   */
  messageLayoutParams.setMargins(minMarginSize, paddingSize,
    minMarginSize, maxMarginSize);
  message.setLayoutParams(messageLayoutParams);
  message.setTextSize(TypedValue.COMPLEX_UNIT_SP, paddingSize);
  message.setText(R.string.message);
  message.setTextColor(messageTextColor);
  message.setBackgroundColor(messageBackgroundColor);

  RoundedRectangle messageContainer = new RoundedRectangle(this);
  LinearLayout.LayoutParams messageContainerLayoutParams = new LinearLayout.LayoutParams(
    LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
  messageContainerLayoutParams.setMargins(paddingSize, 0, paddingSize, 0);
  messageContainer.setLayoutParams(messageContainerLayoutParams);
  messageContainer.setOrientation(LinearLayout.VERTICAL);
  /*
   * This is one of the calls must made to force a ViewGroup to call its
   * draw method instead of just calling the draw method of its children.
   * This tells the RoundedRectangle to color the the exta space that was
   * put around the View as well as the View. This is exterior color of
   * the RoundedRectangle.
   */
  messageContainer.setBackgroundColor(mainBackgroundColor);
  /*
   * This is one of the calls must made to force a ViewGroup to call its
   * draw method instead of just calling the draw method of its children.
   * This is the interior color of the RoundedRectangle. It must be
   * different than the exterior color of the RoundedRectangle or the
   * RoundedRectangle will not call its draw method.
   */
  messageContainer.setInteriorColor(messageBackgroundColor);
  // Add the message to the RoundedRectangle.
  messageContainer.addView(message);

  //
  LinearLayout main = new LinearLayout(this);
  LinearLayout.LayoutParams mainLayoutParams = new LinearLayout.LayoutParams(
    LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
  main.setLayoutParams(mainLayoutParams);
  main.setOrientation(LinearLayout.VERTICAL);
  main.setBackgroundColor(mainBackgroundColor);
  main.addView(label);
  main.addView(messageContainer);

  setContentView(main);
 }
}

The class for RoundedRectangle layout object is as defined here:

/**
 *  A LinearLayout that draws a rounded rectangle around the child View that was added to it.
 */
package android.example;

import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.widget.LinearLayout;

/**
 * A LinearLayout that has rounded corners instead of square corners.
 * 
 * @author Danny Remington
 * 
 * @see LinearLayout
 * 
 */
public class RoundedRectangle extends LinearLayout {
 private int mInteriorColor;

 public RoundedRectangle(Context p_context) {
  super(p_context);
 }

 public RoundedRectangle(Context p_context, AttributeSet attributeSet) {
  super(p_context, attributeSet);
 }

 // Listener for the onDraw event that occurs when the Layout is drawn.
 protected void onDraw(Canvas canvas) {
  Rect rect = new Rect(0, 0, getWidth(), getHeight());
  RectF rectF = new RectF(rect);
  DisplayMetrics metrics = new DisplayMetrics();
  Activity activity = (Activity) getContext();
  activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
  float density = metrics.density;
  int arcSize = Math.round(density * 10);

  Paint paint = new Paint();
  paint.setColor(mInteriorColor);

  canvas.drawRoundRect(rectF, arcSize, arcSize, paint);
 }

 /**
  * Set the background color to use inside the RoundedRectangle.
  * 
  * @param Primitive int - The color inside the rounded rectangle.
  */
 public void setInteriorColor(int interiorColor) {
  mInteriorColor = interiorColor;
 }

 /**
  * Get the background color used inside the RoundedRectangle.
  * 
  * @return Primitive int - The color inside the rounded rectangle.
  */
 public int getInteriorColor() {
  return mInteriorColor;
 }

}
甚是思念 2024-09-06 06:26:10

我不确定这个问题是否已得到解答,但我今天刚刚解决了同样的问题。 Viet 谈到了上述问题,但没有明确指出检查您的颜色值。如果您像我一样有 J2ME 背景,您可能会将颜色 int 值定义为 0xRRGGBB,因此对于全红色 J2ME 会将其定义为 0xFF0000。但是,在 Android 上这样做将导致 int 值为 0x00FF0000。因为 Android 使用 0xAARRGGBB 格式,所以 0xFF0000 (J2ME) 的值在 Android 中实际上是 (0x00FF0000),这是完全透明的全红色,因此在屏幕上看不到。

我注意到上面的代码中您正在使用 question.setTextColor(R.color.green); 此语句将分配在 R 文件中创建的 id 值,因此它可能是一个具有某些值的高数字如 0x7f050000,其中 Alpha 设置为低于 FULL OPAQUE。尝试使用以下示例:

question.setTextColor( getResources().getColor( R.color.green ) );

这应该将文本颜色设置为 R.color.green 中的值,而不是 R.color.green 的 ID。

I'm not sure if this question has been answered or not, but I just overcame this same issue today. Viet touched on the issue above but did not explicitly point out to check your color values. If you're coming from J2ME background like myself, you might be defining your color int values as 0xRRGGBB, so for full red J2ME would define it as 0xFF0000. However, doing so on Android will result in an int value of 0x00FF0000. Because Android uses the format of 0xAARRGGBB, a value of 0xFF0000 (J2ME) is actually (0x00FF0000) in Android this is full Red color that is COMPLETLY TRANSPARENT, so it's not seen on screen.

I Noticed above in your code you're using question.setTextColor(R.color.green); This statement will assign the id value created in the R file, so it's probably a high number with some value as 0x7f050000 where the Alpha is set lower than FULL OPAQUE. Try your example with:

question.setTextColor( getResources().getColor( R.color.green ) );

This should set the text color to the value in R.color.green not the ID of R.color.green.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文