2012-10-16 76 views
0

我使用Eclipse嚮導創建了一個ActionBar和選項卡的活動。我想在我的三個選項卡中顯示ListView,但是如果它們在運行我的應用程序時未顯示。在Android 4中使用ActionBar與Tabs時不顯示ListView in Fragment

與選項卡中的活動代碼:

public class CreateProjectManually extends FragmentActivity implements ActionBar.TabListener { 

    /** 
    * The {@link android.support.v4.view.PagerAdapter} that will provide fragments for each of the 
    * sections. We use a {@link android.support.v4.app.FragmentPagerAdapter} derivative, which will 
    * keep every loaded fragment in memory. If this becomes too memory intensive, it may be best 
    * to switch to a {@link android.support.v4.app.FragmentStatePagerAdapter}. 
    */ 
    SectionsPagerAdapter mSectionsPagerAdapter; 

    /** 
    * The {@link ViewPager} that will host the section contents. 
    */ 
    ViewPager mViewPager; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_create_project_manually); 
     // Create the adapter that will return a fragment for each of the three primary sections 
     // of the app. 
     mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager()); 

     // Set up the action bar. 
     final ActionBar actionBar = getActionBar(); 
     // set the app icon as an action to go home 
     actionBar.setDisplayHomeAsUpEnabled(true); 
     //enable tabs in actionbar 
     actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); 

     // Set up the ViewPager with the sections adapter. 
     mViewPager = (ViewPager) findViewById(R.id.pager); 
     mViewPager.setAdapter(mSectionsPagerAdapter); 

     // When swiping between different sections, select the corresponding tab. 
     // We can also use ActionBar.Tab#select() to do this if we have a reference to the 
     // Tab. 
     mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() { 
      @Override 
      public void onPageSelected(int position) { 
       actionBar.setSelectedNavigationItem(position); 
      } 
     }); 

     // For each of the sections in the app, add a tab to the action bar. 
     for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) { 
      // Create a tab with text corresponding to the page title defined by the adapter. 
      // Also specify this Activity object, which implements the TabListener interface, as the 
      // listener for when this tab is selected. 
      actionBar.addTab(
        actionBar.newTab() 
          .setText(mSectionsPagerAdapter.getPageTitle(i)) 
          .setTabListener(this)); 
     } 
    } 

    /** 
    * Actionbar 
    * */ 
    @Override 
    public boolean onOptionsItemSelected(MenuItem item) { 
     switch (item.getItemId()) { 
     case R.id.menu_save: 
      //TODO Speichern implementieren 
      Toast.makeText(getBaseContext(), "Speichern",Toast.LENGTH_LONG).show(); 
      break; 
     case android.R.id.home: 
      // app icon in action bar clicked; go home 
      Intent intent = new Intent(this, ProjectList.class); 
      intent.putExtra("Uniqid","From_CreateProjectManually_Activity"); 
      intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); 
      startActivity(intent); 
      return true;  
     default: 
      break; 
     } 
     return true; 
    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     getMenuInflater().inflate(R.menu.activity_create_project_manually, menu); 
     return true; 
    } 

    @Override 
    public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { 
    } 

    @Override 
    public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { 
     // When the given tab is selected, switch to the corresponding page in the ViewPager. 
     mViewPager.setCurrentItem(tab.getPosition()); 
    } 

    @Override 
    public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { 
    } 

    /** 
    * A {@link FragmentPagerAdapter} that returns a fragment corresponding to one of the primary 
    * sections of the app. 
    */ 
    public class SectionsPagerAdapter extends FragmentPagerAdapter { 

     public SectionsPagerAdapter(FragmentManager fm) { 
      super(fm); 
     } 

     @Override 
     public Fragment getItem(int i) { 
      Fragment fragment = new DummySectionFragment(); 
      Bundle args = new Bundle(); 
      args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, i + 1); 
      fragment.setArguments(args); 
      return fragment; 
     } 

     @Override 
     public int getCount() { 
      return 3; 
     } 

     @Override 
     public CharSequence getPageTitle(int position) { 
      switch (position) { 
       case 0: return getString(R.string.building).toUpperCase(); 
       case 1: return getString(R.string.room).toUpperCase(); 
       case 2: return getString(R.string.devices).toUpperCase(); 
      } 
      return null; 
     } 
    } 

    /** 
    * A dummy fragment representing a section of the app, but that simply displays dummy text. 
    */ 
    public static class DummySectionFragment extends Fragment { 
     public DummySectionFragment() { 
     } 

     public static final String ARG_SECTION_NUMBER = "section_number"; 

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

      return (LinearLayout) inflater.inflate(R.layout.listviews, container, false); 

     } 
    } 

} 

和XML文件與ListView控件的佈局:

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

    <LinearLayout 
     android:id="@+id/fragment_container" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:orientation="vertical" > 

     <TextView 
      android:id="@+id/textView1" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:text="Medium Text" 
      android:textAppearance="?android:attr/textAppearanceMedium" /> 

     <ListView 
      android:id="@+id/listView1" 
      android:layout_width="match_parent" 
      android:layout_height="259dp" > 
     </ListView> 

    </LinearLayout> 

</LinearLayout> 

TextView的顯示,但沒有的ListView。問題是什麼?

+2

沒有與你的代碼沒有問題,你的列表視圖是空的。你必須在Fragment「DummySectionFragment」上設置和適配你的列表視圖。 –

+0

當然,現在顯示。謝謝! –

+0

@AnisBENNSIR我有同樣的問題butlistview沒有顯示記錄。列表視圖不是空的我已經設置簡單的數組適配器值仍然無法正常工作。我的代碼與上面的代碼片段類似,只是我使用片段作爲容器而不是活動,併爲滑動事件添加了兩個選項卡。 – Swapnil

回答

0

首先,你必須創建你的列表視圖喲有它自己的自定義行,發現它的ID在基於根視圖這樣的onCreateView方法適配器:

@Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
      Bundle savedInstanceState) { 
     View rootView = inflater.inflate(R.layout.fragment_calendar_dummy, 
       container, false); 
     /*TextView dummyTextView = (TextView) rootView 
       .findViewById(R.id.section_label); 
     dummyTextView.setText(Integer.toString(getArguments().getInt(ARG_SECTION_NUMBER)) + "HOLA");*/ 
     //getFavorito(ARG_SECTION_NUMBER); 

     //asyncFavorite().execute(ARG_SECTION_NUMBER); 
     lista = (ListView) rootView.findViewById(R.id.Your own list); 
     loadingLista = (RelativeLayout) rootView.findViewById(R.id.loadingLista); 
     int mes = getArguments().getInt(ARG_SECTION_NUMBER); 
     new asyncFavorite().execute(Integer.toString(mes)); 
     Log.i("mfb", "puse el-----------------" + Integer.toString(mes)); 

     return rootView; 
    } 

在此之後,你要創建一個方法來虛增您的列表,創建一個包含列表中的所有元素的對象的數組列表,並用它來充氣的所有行:

m_orders = new ArrayList<Order>(); 
      //JSONObject data = new JSONObject(Fetcher.getMonthBirthday(FBAccount, params[0])); 
      //resData = data.getJSONArray("data"); 


      //Log.i("mfb", "RESDATA::::::::::" + resData + "////////////////////" +Index.userID); 

      JSONObject objeto = null; 

      String nombre = ""; 
      String cumpliendo = ""; 
      String mes = ""; 
      String dia = ""; 
      String uuid = ""; 

      String favorite = ""; 
      String ownerID = ""; 

      int mesNumero = 0; 

      String[] cumple = null; 
      String pasoMes = ""; 

      for(int i = 0; i<resData.length(); i++){ 
       objeto = resData.getJSONObject(i); 
       nombre = objeto.getString("name"); 
       cumpliendo = objeto.getString("edad"); 

       cumple = objeto.getString("birthday").split("-"); 

       dia = cumple[2]; 
       pasoMes = cumple[1]; 
       mesNumero = Integer.parseInt(pasoMes); 

       //mes = getMes(mesNumero); 

       uuid = objeto.getString("uuid"); 

       favorite = "1"; 
       ownerID = objeto.getString("user_id"); 

       m_orders.add(i, new Order(""+nombre, ""+cumpliendo, ""+mes, ""+dia, "" + uuid, ""+favorite, ""+ownerID, "" + FBAccount));      

       //Log.i("mfb", "HH " + nombre); 

      } 

的,你必須將適配器設置爲您列表

runOnUiThread(new Runnable() { 

       @Override 
       public void run() { 
        try {     
         Log.v("mfb", " Runnable "+m_orders.size()); 
         adapterOrder = new orderItemAdapter(activity.getApplicationContext(), android.R.layout.simple_list_item_1, m_orders); 
         lista.setAdapter(adapterOrder); 
         adapterOrder.notifyDataSetChanged(); 
        }catch (NullPointerException e){ 
         Log.e("Error", " generateAdapter NullPointerException ERROR => "+e.getMessage()); 
        }catch (Exception e) { 
         // TODO: handle exception 
         Log.e("Error", " generateAdapter Exception ERROR => "+e.getMessage()); 
        }      
       } 
      }); 

適配器是這樣的:

public class orderItemAdapter extends ArrayAdapter<Order>{ 
    public ArrayList<Order> orders; 
    LayoutInflater inflater = null; 

    public orderItemAdapter(Context context, int textViewResourceId, ArrayList<Order> orders){ 
     super(context, textViewResourceId, orders); 
     this.orders = orders; 

     Log.v("mfb", "orderItem "+this.orders.size()); 
    } 

    public void add(int index, Order order){ 
     this.orders.add(index, order); 
    } 

    @Override   
    public View getView(int position, View convertView, ViewGroup parent){ 

     View vi=convertView; 
     LayoutInflater inflater = null; 

     if(convertView==null){ 
      inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
      vi = inflater.inflate(R.layout.list_user, null); 
     } 

     Order order = orders.get(position); 
     if(order != null){ 
      TextView nombre = (TextView)vi.findViewById(R.id.nombre); 
      TextView edadCumplir = (TextView)vi.findViewById(R.id.edadCumplir); 
      //TextView mes = (TextView)vi.findViewById(R.id.mes); 
      TextView dia = (TextView)vi.findViewById(R.id.dia); 

      //Log.v("mfb", " order position => "+position); 

      if(nombre != null){ 
       nombre.setText(orders.get(position).getNombre()); 
       //Log.v("mfb", "orderItemAdapter nombre =>" + nombre.getText()); 
      } 

      if(edadCumplir != null){ 
       edadCumplir.setText("Turning " + orders.get(position).getCumpliendo()); 
      } 

      /*if(mes != null){ 
       mes.setText(orders.get(position).getMes()); 
      }*/ 

      if(dia != null){ 
       dia.setText(orders.get(position).getDia()); 
      } 
     }   
     return vi; 
    }    
}