Как можно реализовать добавление большего количества представлений в динамическом макете, реализуя Scrollview в Android

1

Я реализую пользовательский linearlayout в этом добавлении большего количества просмотров, извлекающих базу данных с использованием веб-сервисов в фоновом режиме. Все данные - это сообщения о возврате и связанные с сообщением пользовательские изображения, а также сначала загружают сообщения после однократной загрузки изображений в пользовательском линейном макете

main.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout android:id="@+id/frameLayout1" android:layout_width="fill_parent" android:background="@android:color/white"
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_height="fill_parent">
    <ScrollView android:id="@+id/scrollView1" android:layout_height="wrap_content" android:layout_width="fill_parent">
        <LinearLayout android:layout_width="fill_parent" android:id="@+id/linearLayout2" android:layout_height="fill_parent">
            <LinearLayout android:layout_width="fill_parent" android:id="@+id/linearLayout3" android:layout_height="fill_parent">
                <ImageView android:id="@+id/person" android:layout_width="wrap_content" android:layout_height="wrap_content"></ImageView>
                <TextView android:textColor="@android:color/black" android:id="@+id/textView1" android:layout_height="wrap_content" android:layout_width="wrap_content"></TextView>
            </LinearLayout>
        </LinearLayout>
    </ScrollView>
</FrameLayout>

CodeFile:

public class MYlist extends Activity 
{
    /** Called when the activity is first created. */
    List<MessageClass> messages;
    int i=0,n=5;
     ParseXMLString parse=new ParseXMLString();
     DataParsingComm dataparsing=new DataParsingComm();
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        String xml="<spGetUserMessages><SearchLocation></SearchLocation><LoginUserID>125</LoginUserID></spGetUserMessages>";
        messages =parse.GetGetUserMessages(dataparsing.ILGetUserMessages(xml));


        addElements(messages,i,n);
    }

    protected void addElements(final List<MessageClass> messages2,int i,int n) 
    {
        int k=0;
     //((LinearLayout)findViewById(R.id.linearLayout1)).removeAllViews();

        for(int i1=i;i1<n;i1++)
        {
            LinearLayout ll1=((LinearLayout)findViewById(R.id.linearLayout2));
            ll1.setBackgroundResource(R.drawable.tabmessage);
            Log.v("11111111","333"+ i1+ n);
          if(k==i1)
          {
            for(int j1=i1;j1<n;j1++)
            {

            TextView msg=((TextView)findViewById(R.id.textView1));
            msg.setText(messages2.get(j1).getmessage());

            }
          }
            ImageView prsnImg=((ImageView)findViewById(R.id.person));
        try{
            String photoXml="<spGetUserPhoto><UserID>125</UserID></spGetUserPhoto>";

            String photoInfoFromDB=new DataParsingComm().ILGetImage(photoXml);

            if(photoInfoFromDB.equalsIgnoreCase("anyType{}")||photoInfoFromDB.equals(null) )
            {
                prsnImg.setImageResource(R.drawable.person);
            }
            else{

                byte[] imgArry= Base64.decode(photoInfoFromDB);

                Bitmap bit=BitmapFactory.decodeByteArray(imgArry,0,imgArry.length);

                prsnImg.setImageBitmap(bit);
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
        finally
            {
                System.gc();
                System.runFinalization();
            }

        }

    }
}

снимок экрана: http://www.freeimagehosting.net/uploads/8437c22cca.png

моя проблема - каждый раз, когда отображается один элемент, все данные переопределяют представление одного элемента в макете, как можно реализовать один за другим отображения в линейном макете

скажите, пожалуйста, какое-то решение заблаговременно

Теги:
views
android-linearlayout

1 ответ

1
Лучший ответ

Это потому, что вы всегда выбираете те же два объекта...

Существует очень простой способ получить то, что, я думаю, вам может понадобиться:

main.xml

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/frameLayout1" 
    android:layout_width="fill_parent" 
    android:background="@android:color/white" 
    android:layout_height="fill_parent">
    <ScrollView android:id="@+id/scrollView1" 
        android:layout_height="wrap_content" 
        android:layout_width="fill_parent">

    </ScrollView>
</FrameLayout>

.java

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        ScrollView scrollView = (ScrollView) findViewById(R.id.scrollView1);

        LinearLayout topLinearLayout = new LinearLayout(this);
        topLinearLayout.setOrientation(LinearLayout.VERTICAL); 

        for (int i = 0; i < 15; i++){

            LinearLayout linearLayout = new LinearLayout(this);
            linearLayout.setOrientation(LinearLayout.HORIZONTAL); 

            ImageView imageView = new ImageView (this);
            TextView textView = new TextView (this);

            imageView.setImageResource(R.drawable.image);
            textView.setText("Text View #" + i);

            linearLayout.addView(imageView);
            linearLayout.addView(textView);

            topLinearLayout.addView(linearLayout);          

        }

        scrollView.addView(topLinearLayout);

    }

Вы также можете определить объект topLinearLayout в XML файле. Это зависит от вас.

  • 0
    привет, я добавил просмотров, но не работает
  • 0
    Я обновил свой ответ некоторым базовым кодом, который вы можете найти полезным.

Ещё вопросы

Сообщество Overcoder
Наверх
Меню