Android - LazyAdapter перекрывающиеся представления - PullRequest
4 голосов
/ 04 января 2012

Я делаю ленивую загрузку для отображения изображений и текста. Я получил все и теперь, пытаясь добавить текстовое представление в представлении. Тем не менее, мой адаптер перекрывает мой взгляд. Проще говоря, это то, что просмотр списка перекрывает текстовое представление. Я не уверен, где я делаю это неправильно, потому что оригинальный пример может отображать кнопку чуть ниже списка, но я не могу. Я не получаю никаких ошибок. Мой список просто покрывает весь экран. Есть идеи, в чем может быть проблема?

main.java

public class main extends Activity {

private static final String targetURL ="http://www.google.com/images";
ListView list;

ProgressDialog dialog;
private String[] mStrings = {};
private String[] dStrings = {};
//TextView tv;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);         
    new TheTask().execute();
    list=(ListView)findViewById(R.id.list);
    TextView tv = (TextView)findViewById(R.id.tv);

    //tv.setText("Text View is displayed");
}   


protected class TheTask extends AsyncTask<Void, Void, MyResultClass >{

    protected void onPreExecute() {
        dialog = ProgressDialog.show(Cats.this, "Retrieving Information", "Please wait for few seconds...", true, false);
        dialog.setCancelable(true);
    }

    protected MyResultClass doInBackground(Void... params) {
        searchContent();
        MyResultClass result = new MyResultClass();
        result.mStrings = mStrings;
        result.dStrings = dStrings;
        return result;
    }   

    protected void onPostExecute(MyResultClass result) {            
        dStrings = result.dStrings;
        mStrings = result.mStrings;         
        LazyAdapter adapter = new LazyAdapter(Cats.this, mStrings, dStrings);
        list.setAdapter(adapter);
        dialog.dismiss();
    }       
}

    class MyResultClass
    { 
        public String[] mStrings; 
        public String[] dStrings; 
    }

public void searchContent()
{
    String imageC = "";
    String textC = "";

    try {

        URL url = new URL(targetURL);

        // Make the connection
        URLConnection conn = url.openConnection();
        BufferedReader reader = new BufferedReader(
         new InputStreamReader(conn.getInputStream()));

        String line = reader.readLine();
        Pattern sChar = Pattern.compile("&.*?;");
        line.replaceAll("\\<.*?\\>", "");
        Matcher msChar = sChar.matcher(line);
        while (msChar.find()) line = msChar.replaceAll("");

        while (line != null) {

            if(line.contains("../../"))
            {

                int startIndex = line.indexOf("../../") + 6;
                int endIndex = line.indexOf(">", startIndex + 1);
                String abc = "http://www.google.com/";
                String imageSrc = line.substring(startIndex,endIndex);
                //complete full url
                String xyz = abc +imageSrc;
                xyz = xyz.substring(0,xyz.indexOf('"'));
                xyz = xyz +";";
                xyz = xyz.replaceAll(" ", "%20");
                imageC += xyz;                  
                mStrings = imageC.split(";");
                line = reader.readLine();
            }

            if(line.contains("../../") == false)
            {
                line = reader.readLine();
            }

            if (line.contains("Gnametag"))
            {
                int startIndex = line.indexOf("Gnametag") + 10;
                int endIndex = line.indexOf("<", startIndex + 1);
                String gname = line.substring(startIndex,endIndex);
                textC = textC.replaceAll("</span>", "");
                textC += "Name: "+gname+ "\n";
            }

                if (line.contains("Age"))
                {
                    textC += "Age: "+reader.readLine() + "\n" + ";";
                    textC = textC.replaceAll("                  ", "");
                    dStrings = textC.split(";");
                }

            if (line.contains("Last Update"))
            {
                reader.close();
            }                               
        }           

        // Close the reader
        reader.close();

    } catch (Exception ex) {
        ex.printStackTrace();           
    }     

}
}

Adapter.java

public View getView(int position, View convertView, ViewGroup parent) {
    View vi=convertView;
    ViewHolder holder;
    if(convertView==null){
        vi = inflater.inflate(R.layout.item, null);
        holder=new ViewHolder();
        holder.text=(TextView)vi.findViewById(R.id.text);;
        holder.image=(ImageView)vi.findViewById(R.id.image);
        vi.setTag(holder);
    }
    else
        holder=(ViewHolder)vi.getTag();

    holder.text.setText(text[position]);
    holder.image.setTag(data[position]);
    imageLoader.DisplayImage(data[position], activity, holder.image);
    return vi;
}

item.xml (используется Adapter.java)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#FFFFFF">
<ImageView
  android:id="@+id/image"
  android:layout_width="90dip"
  android:layout_height="90dip" 
  android:src="@drawable/stub" 
  android:scaleType="centerCrop"
  android:layout_gravity="left|center_vertical" 
  />

<TextView
  android:id="@+id/text"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:gravity="center"
  android:textSize="15dip"/>

</LinearLayout>

main.xml

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#FFFFFF">

<LinearLayout
android:id="@+id/linear1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#FFFFFF">

<TextView
android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Testing 123"
/> 

</LinearLayout>

<LinearLayout
android:id="@+id/linear2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"    
android:layout_below="@+id/linear1"
android:background="#FFFFFF">

<ListView
android:id="@+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="30dp"/>
</LinearLayout>

</RelativeLayout>

Ответы [ 3 ]

4 голосов
/ 10 января 2012

Просто удалите символ + из этой строки

android:layout_below="@+id/linear1"

во втором разделе линейного макета.

0 голосов
/ 14 января 2012

Когда вы говорите, что ListView покрывает весь экран, вы ссылаетесь на результат на реальном телефоне или, например, на предварительный просмотр в Eclipse?Если в последнем случае он отображается правильно, то, скорее всего, проблема в вашем Java-коде.

В любом случае, я не могу воспроизвести вашу проблему ни на одном из них.Однако есть две вещи, которые я бы попробовал:

Во-первых, измените порядок вызовов в методе onCreate() вашей Деятельности.В частности, не выполняйте AsyncTask до тех пор, пока вы не инициализируете ListView, так как вы используете его в onPostExecute().Хотя это, вероятно, не будет иметь значения, вам лучше избегать любых шансов на состояние гонки.

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

    list=(ListView)findViewById(R.id.list);
    TextView tv = (TextView)findViewById(R.id.tv);
    // start task after 'list' is initialized.
    new TheTask().execute();
}   

Во-вторых, файл макета, содержащий ваш ListView, излишне сложен.Желательно, чтобы макеты были максимально простыми и ограничивали вложенность для более плоской иерархии.Вы можете просто избавиться от устаревших LinearLayouts и, если вы предпочитаете работать с ними, изменить родительский элемент на один.Кроме того, android:orientation="vertical" не является допустимым атрибутом для RelativeLayout, поэтому обязательно удалите его.

То же RelativeLayout, но без LinearLayouts:

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

    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Testing 123" />

    <ListView
        android:id="@+id/list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/tv"
        android:layout_marginBottom="30dp" />

</RelativeLayout>

То же поведение, но с LinearLayout в качестве корневого элемента:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#FFFFFF"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Testing 123" />

    <ListView
        android:id="@+id/list"
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:layout_marginBottom="30dp" />

</LinearLayout>
0 голосов
/ 07 января 2012

Добавьте android:layout_alignParentTop="true" в топ LinearLayout (linear1)

<LinearLayout
    android:id="@+id/main_xml_linearlayout_one"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    >

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

<LinearLayout
    android:id="@+id/main_xml_linearlayout_two"
    android:layout_below="@id/main_xml_linearlayout_one"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="#FFFFFF" >

    <ListView
        android:id="@+id/main_xml_listview_list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="30dp"/>

</LinearLayout>

...