简体   繁体   中英

ListView with custom adapter doesn't appear

I work in an app in which I want to display in top the month and a left/right arrow for the previous/next months. So far so good.

Down of the month, I want to display a List of names. This is for now. My app is in the first stages. Looks easy but the list doesn't appear and I can't figure out why.

Here is a preview of the screen.

应用程序屏幕预览

Here is all the classes and layouts I use.

MainActivity.java

package team.proodeutikiekriksitoumpas;


import java.util.ArrayList;
import java.util.GregorianCalendar;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class MainActivity extends Activity {

    public GregorianCalendar month, itemmonth;// calendar instances.

    ListView NamesListView, DataListView;
    ArrayList<String> NamesFeedList, DataFeedList;
    MyNamesAdapter NamesAdapter;
    //, DataAdapter;

    //public CalendarAdapter adapter;// adapter instance
    public Handler handler;// for grabbing some event values for showing the dot marker.
    //public ArrayList<String> items; // container to store calendar items which needs showing the event marker


    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //DataListView = (ListView) findViewById(R.id.DataListView);

        NamesFeedList = new ArrayList<String>();
        NamesFeedList.add("Kostis A");
        NamesFeedList.add("Apostolis B");
        NamesAdapter = new MyNamesAdapter(this, R.layout.name_item_view, R.id.name, NamesFeedList);

        NamesListView = (ListView) findViewById(R.id.NamesListView);
        NamesListView.setAdapter(NamesAdapter);
        /*
        DataFeedList = new ArrayList<String>();
        DataFeedList.add("Ok");
        DataFeedList.add("Ok");
        DataAdapter = new ArrayAdapter<String>(this, R.layout.data_item_view, R.id.data, DataFeedList);
        DataListView.setAdapter(DataAdapter);
        */
        month = (GregorianCalendar) GregorianCalendar.getInstance();
        itemmonth = (GregorianCalendar) month.clone();

        //Sitems = new ArrayList<String>();
        //adapter = new CalendarAdapter(this, month);

        handler = new Handler();
        //handler.post(calendarUpdater);

        TextView title = (TextView) findViewById(R.id.title);
        title.setText(android.text.format.DateFormat.format("MMMM yyyy", month));

        RelativeLayout previous = (RelativeLayout) findViewById(R.id.previous);
        previous.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                setPreviousMonth();
                refreshCalendar();
            }
        });

        RelativeLayout next = (RelativeLayout) findViewById(R.id.next);
        next.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                setNextMonth();
                refreshCalendar();

            }
        });
    }

    protected void setNextMonth() {
        if (month.get(GregorianCalendar.MONTH) == month
                .getActualMaximum(GregorianCalendar.MONTH)) {
            month.set((month.get(GregorianCalendar.YEAR) + 1),
                    month.getActualMinimum(GregorianCalendar.MONTH), 1);
        } else {
            month.set(GregorianCalendar.MONTH,
                    month.get(GregorianCalendar.MONTH) + 1);
        }

    }

    protected void setPreviousMonth() {
        if (month.get(GregorianCalendar.MONTH) == month
                .getActualMinimum(GregorianCalendar.MONTH)) {
            month.set((month.get(GregorianCalendar.YEAR) - 1),
                    month.getActualMaximum(GregorianCalendar.MONTH), 1);
        } else {
            month.set(GregorianCalendar.MONTH,
                    month.get(GregorianCalendar.MONTH) - 1);
        }

    }

    public void refreshCalendar() {
        TextView title = (TextView) findViewById(R.id.title);

        //adapter.refreshDays();
        //adapter.notifyDataSetChanged();
        //handler.post(calendarUpdater); // generate some calendar items

        title.setText(android.text.format.DateFormat.format("MMMM yyyy", month));
    }

    /**
     * public Runnable calendarUpdater = new Runnable() {

        @Override
        public void run() {
            items.clear();

            // Print dates of the current week
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd",Locale.US);
            String itemvalue;
            for (int i = 0; i < 7; i++) {
                itemvalue = df.format(itemmonth.getTime());
                itemmonth.add(GregorianCalendar.DATE, 1);
                items.add("2012-09-12");
                items.add("2012-10-07");
                items.add("2012-10-15");
                items.add("2012-10-20");
                items.add("2012-11-30");
                items.add("2012-11-28");
            }

            //adapter.setItems(items);
            //adapter.notifyDataSetChanged();
        }
    };
    **/
}

MyNamesAdapter.java

package team.proodeutikiekriksitoumpas;

import java.util.ArrayList;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

public class MyNamesAdapter extends ArrayAdapter<String> {

    // declaring our ArrayList of Strings
    private ArrayList<String> objects;

    public MyNamesAdapter(Context context, int resource, int textViewResourceId, ArrayList<String> objects) {
        super(context, resource, textViewResourceId, objects);
        this.objects = objects;
        Log.v(null, "listaaaaaaaaa");
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        //return super.getView(position, convertView, parent);

        // assign the view we are converting to a local variable
        View v = convertView;

        // first check to see if the view is null. if so, we have to inflate it.
        // to inflate it basically means to render, or show, the view.
        if (v == null) {
            LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            v = inflater.inflate(R.layout.name_item_view, null);
        }

        /*
         * Recall that the variable position is sent in as an argument to this method.
         * The variable simply refers to the position of the current object in the list. 
         * (The ArrayAdapter iterates through the list we sent it)
         * 
         * Therefore, s refers to the current String object.
         */
        String s = null;
        if(objects != null) {
            s = objects.get(position);
            Log.v(null, s);
        }
        else{
            Log.v(null, "null objects");
        }

        if (s != null) {
            Log.v(null, "to textviews");
            // This is how you obtain a reference to the TextViews.
            // These TextViews are created in the XML files we defined.
            TextView name = (TextView) v.findViewById(R.id.name);

            // check to see if each individual textview is null.
            // if not, assign some text!
            if (name != null){
                name.setText(s);
            }
        }

        return v;
    }


}

activity_main.xmml

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

    <RelativeLayout
        android:id="@+id/header"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">

        <RelativeLayout
            android:id="@+id/previous"
            android:layout_width="40dip"
            android:layout_height="30dip"
            android:layout_alignParentStart="true"
            android:layout_alignParentLeft="true" >

            <ImageView
                android:contentDescription="@string/desc"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerInParent="true"
                android:background="@drawable/arrow_left" />
        </RelativeLayout>

        <TextView
            android:id="@+id/title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="5dip"
            android:textColor="#000000"
            android:text="November"
            android:textSize="18sp"
            android:textStyle="bold" />

        <RelativeLayout
            android:id="@+id/next"
            android:layout_width="40dip"
            android:layout_height="30dip"
            android:layout_alignParentEnd="true"
            android:layout_alignParentRight="true" >

            <ImageView
                android:contentDescription="@string/desc"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerInParent="true"
                android:background="@drawable/arrow_right" />
        </RelativeLayout>
    </RelativeLayout>

    <ListView
        android:id="@+id/NamesListView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </ListView>



</LinearLayout>

name_item_view.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/name"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:text=""
        android:textSize="18sp"
        android:textStyle="bold" />

</LinearLayout>

Thanks in advance.

there are multiple things here:

activity_main.xml change android:orientation="horizontal" to "vertical". As you said before, you want the list to be displayed below.

name_item_view.xml both the layout and the textfield are matching the height. this can be problematic. try having "wrap content" for the text here. also it is not clear on why you actually need a linearlayout wrapped for the textview. maybe try with a simpler version just using the textview. if you want things to be sized, you need something that tells the size. if your list doesnt, then the elements have to. you could have a minimum_height, but it really needs something there to work correctly.

in general you should avoid having listviews using custom length. depending on what exactly you are trying to do it might be perfectly fine to just add those views to a linearlayout if its not that many anyway. otherwise you will have problems very soon. listview is designed to be a size and scrollable - not to be in a scrollcontainer. even though you can make this work, it should be considered a hack. note: in recyclerview this will not be possible anymore it might therefore be a good idea to adjust your layout here to accomodate this.

means here: use all available rest of space for the listview.

now if you like the header to scroll out you have 2 options: make it a header and use whatever way to make this possible you can find (there are libs, do it yourself, etc) make it a toolbar and you can just use the appcompat libs simply to make this toolbar go away when people are scrolling. this might currently be the better solution.

hope it helps

将ListView的android:layout_height从“ wrap_content”更改为xml代码中的某些特定值

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM