ListFragment:应用程序以空视图启动

时间:2014-07-26 13:47:48

标签: java android

我正在尝试在按钮和文本视图下放置一个列表。

代码已经对我有用,但后来我尝试将所有列表复选框标记为选中,从现在开始,当应用程序启动时,我看到空白的黑屏。

线性布局下的我的ListFragment。

这是代码:

main.xml中

<?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:orientation="vertical" >

    <Button
        android:id="@+id/button_date"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/ch_label" />
    <Button
        android:id="@+id/button_start_time"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/ch_start_time_label" />

    <Button
        android:id="@+id/button_end_time"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/ch_end_time_label" />

    <TextView
        android:id="@+id/date_label"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/cur_date"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:id="@+id/text_date"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <DatePicker
        android:id="@+id/date_picker"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TimePicker
        android:id="@+id/start_time_picker"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TimePicker
        android:id="@+id/end_time_picker"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

        <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_weight="1"
        android:orientation="vertical"
        android:id="@+id/c_sms_list">
        </LinearLayout>

</LinearLayout >

row_view.xml

<?xml version="1.0" encoding="utf-8"?>
<CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/checkedTextView1"
    android:layout_width="match_parent"
    android:layout_height="?android:attr/listPreferredItemHeight"
    android:checkMark="?android:attr/listChoiceIndicatorMultiple"
    android:background="?android:attr/activatedBackgroundIndicator" 
    android:text="CheckedTextView" />

MainActivity.java

package com.javacodegeeks.android.datepickerexample;

import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.FragmentManager;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.TimePicker;
import android.app.ListActivity;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.CalendarContract;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import android.support.v4.app.Fragment;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.text.format.DateFormat;
import android.text.format.Time;
import static java.lang.System.out;

public class MainActivity extends FragmentActivity {

    private TextView text_date;
    private DatePicker date_picker;
    private TimePicker start_time_picker;
    private TimePicker end_time_picker;
    private c_sms_list m_fragment_sms_list;
    private Button date_button;
    private Button start_time_button;
    private Button end_time_button;

    private int year;
    private int month;
    private int day;

    private int start_hour;
    private int start_minute;   


    private int end_hour;
    private int end_minute; 

    static final int DATE_DIALOG_ID       = 100;
    static final int START_TIME_DIALOG_ID = 101;
    static final int END_TIME_DIALOG_ID   = 102;

    private Cursor mCursor = null;  
    private static final String[] COLS = new String[] { CalendarContract.Events.TITLE, CalendarContract.Events.DTSTART};


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        m_fragment_sms_list = new c_sms_list();
        setCurrentDate();
        addButtonListener();
        android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction trans = fragmentManager.beginTransaction();
        m_fragment_sms_list.mEventsList = retreive_events();
        trans.add(R.id.c_sms_list, m_fragment_sms_list);
        trans.commit();
        //]4ListView lView  = m_fragment_sms_list.getListView();
        //if (lView != null && lView.getCount()>0) lView.getChildAt(0).setSelected(true);
    }

    // display current date both on the text view and the Date Picker
    public void setCurrentDate() {

        text_date = (TextView) findViewById(R.id.text_date);
        date_picker = (DatePicker) findViewById(R.id.date_picker);
        start_time_picker = (TimePicker) findViewById(R.id.start_time_picker);
        end_time_picker   = (TimePicker) findViewById(R.id.end_time_picker);

        final Calendar calendar = Calendar.getInstance();

        year = calendar.get(Calendar.YEAR);
        month = calendar.get(Calendar.MONTH);
        day = calendar.get(Calendar.DAY_OF_MONTH);
        start_hour = 7;
        start_minute = 0;
        end_hour = 18;
        end_minute = 0;

        String date_string = new StringBuilder()
                                .append(day).append("-")
                                .append(month + 1).append("-")
                                .append(year).append(" ").toString();
        String start_time_string = new StringBuilder()
                                .append(" START time ")
                                .append(pad(start_hour)).append(":")    
                                .append(pad(start_minute)).append(" ").toString();  

        String end_time_string = new StringBuilder()
                                .append(" END    time ")
                                .append(pad(end_hour)).append(":")  
                                .append(pad(end_minute)).append(" ").toString();        

        // set current date into textview
        text_date.setText(new StringBuilder()
            // Month is 0 based, so you have to add 1
            .append(date_string)
            .append(start_time_string)
            .append(end_time_string)
            );

        // set current date into Date Picker
        date_picker.init(year, month, day, null);
        date_picker.setVisibility(DatePicker.GONE);
        date_button = (Button) findViewById(R.id.button_date);
        date_button.setText(date_string);       
        start_time_button = (Button) findViewById(R.id.button_start_time);
        end_time_button = (Button) findViewById(R.id.button_end_time);          
        initTimePickerAndButton(start_time_picker, start_hour, start_minute, start_time_button, start_time_string);
        initTimePickerAndButton(end_time_picker, end_hour, end_minute, end_time_button, end_time_string);
    }

    public void addButtonListener() {

        // Date Picker
        date_button = (Button) findViewById(R.id.button_date);

        date_button.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                showDialog(DATE_DIALOG_ID);

            }

        });
        // Start Time Picker
        start_time_button = (Button) findViewById(R.id.button_start_time);

        start_time_button.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                showDialog(START_TIME_DIALOG_ID);

            }
        });             
        // End Time Picker
        end_time_button = (Button) findViewById(R.id.button_end_time);

        end_time_button.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                showDialog(END_TIME_DIALOG_ID);

            }           

        });     


    }
    @Override
    protected Dialog onCreateDialog(int id) {

        switch (id) {
        case DATE_DIALOG_ID:
           // set date picker as current date
           return new DatePickerDialog(this, datePickerListener, year, month,day);
        case START_TIME_DIALOG_ID:
           // set date picker as current date
           return new TimePickerDialog(this, startTimePickerListener, start_hour, start_minute, false);
        case END_TIME_DIALOG_ID:
               // set date picker as current date
               return new TimePickerDialog(this, endTimePickerListener, end_hour, end_minute, false);          
        }       
        return null;
    }


    private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {

        // when dialog box is closed, below method will be called.
        public void onDateSet(DatePicker view, int selectedYear,int selectedMonth, int selectedDay) {
            year = selectedYear;
            month = selectedMonth;
            day = selectedDay;

            // set selected date into Text View
            text_date.setText(new StringBuilder()
                // Month is 0 based, so you have to add 1
                .append(day).append("-")
                .append(month + 1).append("-")
                .append(year).append(" ")
                .append(year).append(" at time ")
                .append(pad(start_hour)).append(":")    
                .append(pad(start_minute)).append(" ")
                    );

            // set selected date into Date Picker
            date_picker.init(year, month, day, null);           
            // update list
            ArrayList<String> updated_events = retreive_events();
            m_fragment_sms_list.mEventsList.clear();
            m_fragment_sms_list.mEventsList.addAll(updated_events);
            //m_fragment_sms_list.update_list();

            m_fragment_sms_list.mArrayAdapter.notifyDataSetChanged();

        }
    };


        private TimePickerDialog.OnTimeSetListener startTimePickerListener =  new TimePickerDialog.OnTimeSetListener() {
            public void onTimeSet(TimePicker view, int selectedHour, int selectedMinute) {
                start_hour = selectedHour;
                start_minute = selectedMinute;

                String date_string = new StringBuilder()
                                        .append(day).append("-")
                                        .append(month + 1).append("-")
                                        .append(year).append(" ").toString();
                String start_time_string = new StringBuilder()
                                        .append(" start time ")
                                        .append(pad(start_hour)).append(":")    
                                        .append(pad(start_minute)).append(" ").toString();  

                String end_time_string = new StringBuilder()
                                        .append(" start time ")
                                        .append(pad(end_hour)).append(":")  
                                        .append(pad(end_minute)).append(" ").toString();        

                // set current date into textview
                text_date.setText(new StringBuilder()
                    // Month is 0 based, so you have to add 1
                    .append(date_string)
                    .append(start_time_string)
                    .append(end_time_string)
                    );

                initTimePickerAndButton(start_time_picker, start_hour, start_minute, start_time_button, start_time_string);

            }
        };

        private TimePickerDialog.OnTimeSetListener endTimePickerListener =  new TimePickerDialog.OnTimeSetListener() {
            public void onTimeSet(TimePicker view, int selectedHour, int selectedMinute) {
                end_hour = selectedHour;
                end_minute = selectedMinute;

                String date_string = new StringBuilder()
                                        .append(day).append("-")
                                        .append(month + 1).append("-")
                                        .append(year).append(" ").toString();
                String start_time_string = new StringBuilder()
                                        .append(" start time ")
                                        .append(pad(start_hour)).append(":")    
                                        .append(pad(start_minute)).append(" ").toString();  

                String end_time_string = new StringBuilder()
                                        .append(" start time ")
                                        .append(pad(end_hour)).append(":")  
                                        .append(pad(end_minute)).append(" ").toString();        

                // set current date into textview
                text_date.setText(new StringBuilder()
                    // Month is 0 based, so you have to add 1
                    .append(date_string)
                    .append(start_time_string)
                    .append(end_time_string)
                    );
                    initTimePickerAndButton(end_time_picker, end_hour, end_minute, end_time_button, end_time_string);

            }
        };

        private static String pad(int c) {
            if (c >= 10)
               return String.valueOf(c);
            else
               return "0" + String.valueOf(c);
        }

        private void initTimePickerAndButton(TimePicker time_picker, int hour, int minute, Button time_button, String time_string) {
            time_picker.setVisibility(TimePicker.GONE);
            time_picker.setIs24HourView(Boolean.TRUE);
            time_picker.setCurrentHour(hour);
            time_picker.setCurrentMinute(minute);
            time_button.setText(time_string);       

            int a;
            a=5;
        }

        // ==================================
        // CALENDAR HANDLING
        // ==================================       
        ArrayList<String> retreive_events() {
             Log.d("SHIMI", "SHALOM SHALOM");
            Calendar c_start= Calendar.getInstance();
            c_start.set(2014,3,7,0,0); //Note that months start from 0 (January)   
            Calendar c_end=  Calendar.getInstance();
            c_end.set(2014,3,7,0,0); //Note that months start from 0 (January)

            Time t = new Time();

            //t.setToNow();
            t.set(0, start_minute, start_hour, day, month, year);
            String dtStart = Long.toString(t.toMillis(false));
            t.set(59, end_minute, end_hour, day, month, year);
            String dtEnd = Long.toString(t.toMillis(false));

            String selection = "((" + CalendarContract.Events.DTSTART + " <= ?) AND (" + CalendarContract.Events.DTEND + " >= ?))";

            String[] selectionArgs = new String[] { dtEnd, dtStart};


            Log.d("SHIMI", "got here before query");
            mCursor =  getContentResolver().query(CalendarContract.Events.CONTENT_URI, COLS, selection, selectionArgs, null);
            Log.d("SHIMI", "got here after query");
            mCursor.moveToFirst();
            Log.d("SHIMI", "got here after query 2");
            return from_cursor_to_string_arr();
        }


        ArrayList<String>  from_cursor_to_string_arr() {
            Log.d("SHIMI", "start of to string array");
            ArrayList<String> string_arr = new ArrayList<String>();
            String title = "N/A";
            Long start = 0L;
            while(!mCursor.isLast()) {

                Format df = DateFormat.getDateFormat(this);
                SimpleDateFormat sdf = new SimpleDateFormat("dd/MM");
                Format tf = DateFormat.getTimeFormat(this);
                try {
                    title = mCursor.getString(0);
                    start = mCursor.getLong(1);
                } catch (Exception e) {
                    //ignore
                }

                String event_details_str = new StringBuilder()
                                                .append(title)
                                                .append(" בתאריך ")
                                                .append(sdf.format(start))  
                                                .append(" בשעה ")
                                                .append(tf.format(start))
                                                .toString();    

                string_arr.add(event_details_str);
                mCursor.moveToNext();
            }
            return string_arr;
        }

}

c_sms_list.java(这是我希望它列出的片段)

package com.javacodegeeks.android.datepickerexample;

import java.util.ArrayList;

import android.app.ListActivity;
import android.support.v4.app.Fragment;
import android.support.v4.app.ListFragment ;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import android.view.View;
import android.widget.ListView;

public class c_sms_list extends ListFragment  {

    ArrayList<String> mEventsList; 
    String[]          mEventListValueArray;
    ArrayAdapter<String> mArrayAdapter;

  @Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //String[] values = new String[] { "a", "b", "c", "d", "e", "f", "g",
    //    "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s",
    //    "t", "u", "w", "x", "y", "z" };
    //CalEventRetreiver cal_event_retreiver = new CalEventRetreiver();
    update_list();
    getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
    setListAdapter(mArrayAdapter);

  }

  void update_list() {
        mEventListValueArray = (String[]) mEventsList.toArray(new String[0]);
        mArrayAdapter = new ArrayAdapter<String>(getActivity(),
            android.R.layout.simple_list_item_multiple_choice, mEventsList);
  }

  @Override
  public void onListItemClick(ListView l, View v, int position, long id) {
    // do something with the data
  }
} 

1 个答案:

答案 0 :(得分:0)

尝试做类似的事情:

  public static class SimpleListFragment extends ListFragment  {  

       String[] numbers_text = new String[] { "one", "two", "three", "four",  
                                              "five", "six", "seven", "eight", 
                                              "nine", "ten", "eleven",  
                                              "twelve", "thirteen", "fourteen",               
                                              "fifteen" };  
       String[] numbers_digits = new String[] { "1", "2", "3", "4", "5", "6", "7",  
                                                "8", "9", "10", "11", "12", "13", 
                                                "14", "15" };  

       @Override  
       public void onListItemClick(ListView l, View v, int position, long id) {  
            new CustomToast(getActivity(), numbers_digits[(int) id]);     
       }  

       @Override  
       public View onCreateView(LayoutInflater inflater, ViewGroup container, 
                                Bundle savedInstanceState) {  

            ArrayAdapter<String> adapter = new ArrayAdapter<String>
                                           (inflater.getContext(),   
                                            android.R.layout.simple_list_item_1,  
                                            numbers_text);  
            setListAdapter(adapter);  
            return super.onCreateView(inflater, container, savedInstanceState);  
       }  
  }