2013-07-13 4 views
1

У меня есть пользовательский класс, который распространяется на класс ViewGroup. Внутри я хочу добавить несколько представлений, включая два буттонов, которые должны быть рядом друг с другом. Я придумал создать XML-файл с этим представлением, а затем добавить его с помощью addView. К сожалению, это не сработает.Добавить LinearLayout в ViewGroup

Моей второй идеей, которая, я думаю, лучше было создавать LineraLayout программно вместе с двумя кнопками, настраивая все настройки, а затем добавляя.

Это код:

//adding view to view group 
addView(createView(ctx)); 

//function creating linearlayout and buttons 
private View createView(Context ctx){ 
     LinearLayout l = new LinearLayout(ctx); 
     l.setOrientation(LinearLayout.HORIZONTAL); 
     l.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT)); 
     Button btnL = new Button(ctx); 
     btnL.setText("Text1"); 
     Button btnR = new Button(ctx); 
     btnR.setText("Text2"); 
     l.addView(btnL); 
     l.addView(btnR); 
     return l; 
    } 

Проблема заключается в том, что я не вижу этой точки зрения в настоящее время на всех. Я имею в виду, что это создано из LinearLayout. В LogCat нет ошибки.

Может кто-нибудь, пожалуйста, скажите мне, что мне нужно сделать, чтобы добавить его?

EDIT:

Это код onLayout, у меня нет onMeasure:

@Override 
    protected void onLayout(boolean changed, int l, int t, int r, int b) { 
     int w = getWidth(); 
     int h = getHeight(); 
     for (int i = 0; i < NUM_CHILDREN; i++) { 
      View v = getChildAt(i); 
      int ii = i * 4; 
      float fl = w * COORDS[ii]/GRID_WIDTH; 
      float ft = h * COORDS[ii + 1]/GRID_HEIGHT; 
      float fr = fl + w * COORDS[ii + 2]/GRID_WIDTH; 
      float fb = ft + h * COORDS[ii + 3]/GRID_HEIGHT; 
      v.layout(Math.round(fl), Math.round(ft), Math.round(fr), 
        Math.round(fb)); 
     } 
    } 

В общем, я просто используя огромный стол, где я получил информацию, что точные размеры даны вид должен быть.

+0

Это помогло бы увидеть код для '' onMeasure' и onLayout' методы пользовательских 'ViewGroup'. – Luksprog

+0

@Luksprog только что добавил. – sebap123

+0

Почему у вас первая идея с загрузкой двух кнопок из xml не работает? –

ответ

4

переопределить пользовательские ViewGroup в onMeasure(), как это:

@Override 
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 
    int w = getWidth(); 
    int h = getHeight(); 
    for (int i = 0; i < NUM_CHILDREN; i++) { 
     View v = getChildAt(i); 
     int ii = i * 4; 
     float fw = w * COORDS[ii+2]/GRID_WIDTH; 
     float fh = h * COORDS[ii+3]/GRID_HEIGHT; 
     int wSpec = MeasureSpec.makeMeasureSpec(Math.round(fw), MeasureSpec.EXACTLY); 
     int hSpec = MeasureSpec.makeMeasureSpec(Math.round(fh), MeasureSpec.EXACTLY); 
     Log.d(TAG, "onMeasure Width " + MeasureSpec.toString(wSpec) + ", Height " + MeasureSpec.toString(hSpec)); 
     v.measure(wSpec, hSpec); 
    } 
    super.onMeasure(widthMeasureSpec, heightMeasureSpec); 
} 
0

Для вашей первой идеи я даю вам пример из моего проекта, как вы просили.

Он основан на простой идее. У меня есть элемент, созданный в файле макета xml. Я загружаю его из файла макета xml. Я меняю несколько вещей и, наконец, добавляю их к элементу, который в настоящее время просматривается на экране.

   RelativeLayout relativeLayout = (RelativeLayout) getLayoutInflater().inflate(R.layout.android_messenger_sent_message, null); 
       TextView inbox_message = (TextView)relativeLayout.findViewById(R.id.sentMessage); 
       inbox_message.setText(conversationInfo.getBody()); 

       TextView inbox_messageStatus = (TextView) relativeLayout.findViewById(R.id.sentMessageStatus); 
      String dateStatus = getDateForStatus(conversationInfo.getDateSent()); 
      inbox_messageStatus.setText(""+dateStatus+" "+getString(R.string.me)); 

       linearLayoutGlobal.addView(relativeLayout,0); 

Файл формата XML отсюда ниже.

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" > 

    <ImageView 
     android:id="@+id/imageView1" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_alignParentLeft="true" 
     android:layout_alignParentTop="true" 
     android:paddingLeft="10dp" 
     android:paddingTop="10dp" 
     android:paddingRight="10dp" 
     android:paddingBottom="2dp" 
     android:src="@drawable/contact_ico" /> 
    <LinearLayout 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_marginTop="10dp" 
     android:layout_marginRight="5dp" 
     android:layout_toRightOf="@+id/imageView1" 
     android:background="@color/light_blue" 
     android:orientation="vertical"> 
     <TextView 
      android:id="@+id/sentMessageStatus" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:text="12:59, FirstName LastName" 
      android:textColor="@android:color/darker_gray" 
      android:paddingBottom="5dp"/> 
     <TextView 
      android:id="@+id/sentMessage" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:text="This is a long sample message and what if it will be toooooooo long?" 
      /> 
    </LinearLayout> 

</RelativeLayout> 
+0

Можете ли вы также показать, как вы создаете 'linearLayoutGlobal', потому что я думаю, что есть проблема, с которой я борюсь. И, во-вторых, я полагаю, что ваш код находится внутри Activity, и поскольку я использую класс, расширяющий ViewGroup, это бесполезно. – sebap123

Смежные вопросы