Android LinearLayout无法添加多个视图程序

时间:2013-12-15 22:37:11

标签: android layout view

我正在尝试使用此代码添加多个自定义视图(现在它们是简单的矩形)

            //Defining the layout

    HandLayout = new LinearLayout(this);
    HandLayout.setOrientation(LinearLayout.HORIZONTAL);
    HandLayout.setBackgroundColor(getResources().getColor(R.color.bg_hand));
    HandLayout.setLayoutParams(new   LayoutParams(getResources().getInteger(R.integer.dim_hand_width), getResources().getInteger(R.integer.dim_hand_height)));


            //Some more code

    int dx = getResources().getInteger(R.integer.dim_cardslot_width);
    for (int i = 0; i < 6; i++){
        Card c = new Card(this,i);
        HandLayout.addView(c);  
        c.setX(i*dx);
    }

问题在于,我只看到第一个矩形而不是另外一个6个矩形。

我认为矩形在那里但是在第一个绘制的矩形“后面”。如何告诉视图将它们“移动”到右边?

感谢您的帮助

编辑:我认为问题在于卡类代码。在得到其中一位用户的建议后,我尝试添加TextViews并且他们工作了。这是卡类的代码(注意,唯一不存在的代码是一堆常量int的声明)。

public Card(Context context, int id) {
    super(context);
    // TODO Auto-generated constructor stub
    borders = new Rect(0,0,
            getResources().getInteger(R.integer.dim_cardslot_width),
            getResources().getInteger(R.integer.dim_cardslot_height));

    offw = (getResources().getInteger(R.integer.dim_cardslot_width) - getResources().getInteger(R.integer.dim_card_width))/2;
    offh = (getResources().getInteger(R.integer.dim_cardslot_height) - getResources().getInteger(R.integer.dim_card_height))/2;

    cborders = new RectF((float)offw, (float)offh, 
            (float)getResources().getInteger(R.integer.dim_card_width), 
            (float)getResources().getInteger(R.integer.dim_card_height));

    ntext = Typeface.create(Typeface.MONOSPACE,Typeface.NORMAL);
    paint = new Paint();
}

protected void onDraw(Canvas canvas){
    paint.setColor(getResources().getColor(R.color.bg_card));
    canvas.drawRect(borders, paint);
    paint.setColor(getResources().getColor(R.color.main_card));
    canvas.drawRoundRect(cborders, rad, rad, paint);

    paint.setColor(getResources().getColor(R.color.card_text));
    paint.setTextSize(14);
    canvas.drawText("Card: " + String.valueOf(ID),offw,TopOffset+CharHeight,paint);

}

2 个答案:

答案 0 :(得分:1)

它们不是“落后”,它们彼此“相邻”,我认为每个视图的宽度都是fill_parent这就是为什么你只得到一个视图,试着把你的父布局放在scrollView里面并检查差异

答案 1 :(得分:-1)

XML解决方案:

假设您的卡片设计如下所示

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >

   <TextView
        android:id="@+id/value"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
         />

</LinearLayout>
你的java代码中的

for (int i = 0; i < 6; i++){
   View cardView = LayoutInflater.from(getActivity()).inflate(R.layout.xml_above, null);
   TextView tv = cardView.findViewById(R.id.value));
   tv.setText("your text");

   //if you have click listeners
   tv.setOnClickListener(...);

   HandLayout.addView(cardView); 

}

看起来很简单