2013-02-18 1 views
0

간단한 ListView에 객체 목록을 구현하는 데 문제가있는 것처럼 보입니다.ListFragment를 사용하여 ListView에 대한 객체 배열 만들기

다음은 각 목록 요소에 대한 내 개체 클래스입니다. package com.example.android.fragments;

package com.example.android.fragments; 

public class ListObject { 
    public String objectname; //name of schedule 
    public boolean[] Days = { 
      false, //monday 
      false, //tuesday 
      false, //and soforth 
      false, 
      false, 
      false, 
      false}; 

    public int starthour, startminute, stophour, stopminute; //times from TimePicker 
    public boolean vibrate; 

    public ListObject() 
    { 
     objectname = null; //if doesnt work, do objectname = ""; 
     vibrate = false; 
     starthour = 8; 
     startminute = 0; 
     stophour = 15; 
     stopminute = 0; 
    } 

    public ListObject(String name, boolean[] newdays, boolean vib, int a, int b, int c, int d) 
    { 
     objectname = name; 
     Days = newdays; 
     vibrate = vib; 
     starthour = a; 
     startminute = b; 
     stophour = c; 
     stopminute = d; 
    } 

    @Override 
    public String toString() 
    { 
     String startampm = "am"; 
     String stopampm = "am"; 
     if (starthour > 11) //turns into am/pm 
     { 
      startampm = "pm"; 
      starthour -= 12; 
     } 
     if (stophour > 11) //turns into am/pm 
     { 
      stopampm = "pm"; 
      stophour -= 12; 
     } 

     String daysstring = null ; //initializes string representing days activated 
     for(int i = 0; i < 7; i++) //add into string the correct days 
     { 
      if (Days[i] == true) 
      { 
       if(i == 0) 
        daysstring += "M, "; 
       else if (i == 1) 
        daysstring += "Tu, "; 
       else if (i == 2) 
        daysstring += "W, "; 
       else if (i == 3) 
        daysstring += "Th, "; 
       else if (i == 4) 
        daysstring += "F, "; 
       else if (i == 5) 
        daysstring += "Sa, "; 
       else 
        daysstring += "Su, "; 
      } 
     } 
     daysstring = daysstring.substring(0, daysstring.length() - 3); //removes the last ', ' 
     daysstring += ": "; 

     String timestring = 
       starthour + ":" + startminute + " " + startampm + " - " + 
       stophour + ":" + stopminute + " " + stopampm; 

     return objectname + "\n" + daysstring + timestring; 
    } 

} 

내 주요 활동은 FrameLayout이

다음
package com.example.android.fragments; 

import android.os.Bundle; 
import android.support.v4.app.FragmentActivity; 
import android.support.v4.app.FragmentTransaction; 

public class MainActivity extends FragmentActivity 
     implements MainListFragment.OnListSelectedListener { 

    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.mainlayout); 

     // Check whether the activity is using the layout version with 
     // the fragment_container FrameLayout. If so, we must add the first fragment 
     if (findViewById(R.id.fragment_container) != null) { //meaning, if using phone version 

      // However, if we're being restored from a previous state, 
      // then we don't need to do anything and should return or else 
      // we could end up with overlapping fragments. 
      if (savedInstanceState != null) { 
       return; 
      } 

      // Create an instance of ExampleFragment 
      MainListFragment firstFragment = new MainListFragment(); 

      // In case this activity was started with special instructions from an Intent, 
      // pass the Intent's extras to the fragment as arguments 
      firstFragment.setArguments(getIntent().getExtras()); 



      // Add the fragment to the 'fragment_container' FrameLayout 
      getSupportFragmentManager().beginTransaction() 
        .add(R.id.fragment_container, firstFragment).commit(); 
     } 
    } 

    public void onArticleSelected(int position) { 

     // Capture the article fragment from the activity layout 
     InfoFragment articleFrag = (InfoFragment) 
       getSupportFragmentManager().findFragmentById(R.id.article_fragment); //article_fragment exists in layout-large 

     if (articleFrag != null) { 
      // If article frag is available, we're in two-pane layout... 

      // Call a method in the ArticleFragment to update its content 
      articleFrag.updateArticleView(position); 

     } else { 
      // phone layout - swap frags 

      // Create fragment and give it an argument for the selected article 
      InfoFragment newFragment = new InfoFragment(); 
      Bundle args = new Bundle(); 
      args.putInt(InfoFragment.ARG_POSITION, position); 
      newFragment.setArguments(args); 
      FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); 

      // Replace whatever is in the fragment_container view with this fragment, 
      // and add the transaction to the back stack so the user can navigate back 
      transaction.replace(R.id.fragment_container, newFragment); 
      transaction.addToBackStack(null); 

      // Commit the transaction 
      transaction.commit(); 
     } 
    } 
} 

인 mainlayout 할 수있는 레이아웃을 설정하는 문제이고, 응용 프로그램의 시작 오픈 할 예정이다 여기 내 ListFragment에, 단순히 객체의 3을 생성하고 mainlistview의 ListView에 ID를 가지고 내 listlayout.xml에 정의 된 목록보기에 넣어 수 없습니다

package com.example.android.fragments; 

import java.util.ArrayList; 
import java.util.List; 

import android.app.Activity; 
import android.app.ListActivity; 
import android.os.Build; 
import android.os.Bundle; 
import android.support.v4.app.ListFragment; 
import android.view.View; 
import android.widget.ArrayAdapter; 
import android.widget.ListView; 

public class MainListFragment extends ListFragment{ //used to extend ListActivity{ 
    OnListSelectedListener mCallback; 

    // The container Activity must implement this interface so the frag can deliver messages 
    public interface OnListSelectedListener { 
     /** Called by ListFragment when a list item is selected */ 
     public void onArticleSelected(int position); 
    } 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

     // We need to use a different list item layout for devices older than Honeycomb 
     int layout = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB ? 
       android.R.layout.simple_list_item_activated_1 : android.R.layout.simple_list_item_1; 


     //using this now to add properties 
     ListView mainlist = (ListView)getView().findViewById(R.id.mainlistview); 

     //INFO FOR MADE UP OBJECTS 
     boolean[] Days1 = {   
       true, //monday 
       false, //tuesday 
       true, //and soforth 
       false, 
       true, 
       false, 
       false}; 

     boolean[] Days2 = { 
       false, //monday 
       false, //tuesday 
       false, //and soforth 
       false, 
       true, 
       true, 
       true}; 

     boolean[] Days3 = { 
       false, //monday 
       false, //tuesday 
       false, //and soforth 
       true, 
       false, 
       false, 
       false}; 

     //create sample objects 
     ListObject[] scheduleobjs = 
      { 
       new ListObject("Club Practice", Days1, true, 1, 0, 5, 25), 
       new ListObject("Work", Days2, true, 3, 30, 14, 20), 
       new ListObject("Church", Days3, true, 12, 5, 14, 20) 
      }; 

//  String[] liststring = 
//    { 
//     scheduleobjs[0].toString(), 
//     scheduleobjs[1].toString(), 
//     scheduleobjs[2].toString() 
//    }; 
//  ArrayList<ListObject> arraylist; //add objects to arraylist 
//  arraylist.add(scheduleobjs[0]); 
//  arraylist.add(scheduleobjs[1]); 
//  arraylist.add(scheduleobjs[2]); 

     String[] arraylist = new String[] 
       { 
        scheduleobjs[0].toString(), 
        scheduleobjs[1].toString(), 
        scheduleobjs[2].toString() 
       }; 

     ArrayAdapter<String> arrayadapter = new ArrayAdapter<String>(this, layout, arraylist); 
//  setListAdapter(new ArrayAdapter<String>(getActivity(), layout,)) 
     mainlist.setAdapter(arrayadapter); 

     //inflate here??? 
    } 

    @Override 
    public void onStart() { 
     super.onStart(); 

     // When in two-pane layout, set the listview to highlight the selected list item 
     // (We do this during onStart because at the point the listview is available.) 
//  if (getFragmentManager().findFragmentById(R.id.article_fragment) != null) { 
//   getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE); COMMENTED OUT BECAUSE USED IN 2 PANE LAYOUT 
//  } 
    } 

@Override 
public void onAttach(Activity activity) { 
    super.onAttach(activity); 

    // This makes sure that the container activity has implemented 
    // the callback interface. If not, it throws an exception. 
    try { 
     mCallback = (OnListSelectedListener) activity; 
    } catch (ClassCastException e) { 
     throw new ClassCastException(activity.toString() 
       + " must implement OnListSelectedListener"); 
    } 
} 

    @Override 
    public void onListItemClick(ListView l, View v, int position, long id) { 
     // Notify the parent activity of selected item 
     mCallback.onArticleSelected(position); 

     // Set the item as checked to be highlighted when in two-pane layout 
     getListView().setItemChecked(position, true); 
    } 
} 

당신은 내가 주석 한 볼 수 있습니다 이전에 객체 클래스를 사용하여 toString()을 재정의했는데, 어디에서 잘못 되었습니까? 그리고 이것을 구현하는 가장 좋은 방법은 무엇입니까? 이 결국 문자열을 표시하기 때문에 결국 더 나은 listview 만들려면 원하는 및 각 개체에 대한 확인란을 다른 크기와 색이 지정된 텍스트를 원하는하지만 지금은이 작업을 얻으려고.

+0

독자적인 ArrayAdapter 구현을 시도 했습니까? – Naveen

+0

코드를 실행하면 정확히 무엇이 발생합니까? 그것은 추락합니까? 빈 화면이 표시됩니까? ListFragment 클래스를 빠르게 보면 onCreateView를 재정 의하여 절편 레이아웃을로드하지 않아도됩니다. – ebarrenechea

답변

관련 문제