【问题标题】:Android Runtime Layout TutorialAndroid 运行时布局教程
【发布时间】:2010-04-22 19:16:52
【问题描述】:

有没有人知道如何在运行时在 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);
  }
}

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

谢谢

【问题讨论】:

    标签: android runtime android-layout


    【解决方案1】:

    您忘记设置 contentView。你应该添加

    setContentView(layout);
    

    onCreate 方法结束

    【讨论】:

    • @Gab 感谢您的回复。所以我根据你的回答在上面和我的应用程序中编辑了我的代码,但我仍然得到与以前相同的结果,一个带有标题栏的黑屏。
    • @Ryan:将蓝色背景设置为布局并将绿色设置为问题 TextView 怎么样?您没有指明尺寸。
    • @Viet:我已经根据您的建议编辑了上面的问题和代码,但是我仍然得到与标题栏相同的黑屏结果。
    【解决方案2】:

    您可以查看此网址: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);
        }
    }
    

    【讨论】:

    • @Viet:信息量很大的帖子!谢谢!您是对的,它确实可以完美运行,但是我看不出您在上面发布的内容与我的代码之间有什么根本不同?如果可以的话,请帮我看看有什么不同!
    • @Viet:好的,如果我像您的示例一样将其保留为非常简单的骨架,它可以工作,我会在黑色线性布局上得到白色文本。但是,如果像在我的代码中一样,我尝试设置 LinearLayout 或 TextView 的属性,例如布局上的背景颜色或 textview 上的文本颜色,它们似乎没有采用。无论我将什么颜色传递给 layout.setBackgroundColor(),布局的背景总是显示为黑色,当我尝试在文本视图上设置文本颜色()时,它总是默认为黑色(我看不到,因为布局为黑色)或文本不显示。
    • @Ryan:您设置的背景不是正确的 ARGB 格式 :) 现在检查更新的代码 :)
    • @Viet:谢谢,我刚刚在这里找到了另一个问题来解决这个问题(stackoverflow.com/questions/1466788/…)。为什么我不能只使用 colors.xml 资源文件 (R.color.xxxx) 中的值?
    • 嗯,您需要确保您定义的那些颜色遵循 ARGB 格式。
    【解决方案3】:

    以下演示如何在不使用布局 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;
     }
    
    }
    

    【讨论】:

      【解决方案4】:

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

      我在上面的代码中注意到您正在使用question.setTextColor(R.color.green); 此语句将分配在 R 文件中创建的 id 值,因此它可能是一个较高的数字,其中 Alpha 设置为低于完全不透明的 0x7f050000。试试你的例子:

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

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

      【讨论】:

        猜你喜欢
        • 2011-04-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-04-21
        • 1970-01-01
        相关资源
        最近更新 更多