2

我对android开发很陌生。我正在尝试使用选项卡(通过片段添加)构建应用程序。在其中一个片段(Sector1)中,我试图显示一个 ListView。此列表已使用我从 ArrayAdapter 扩展的 UserCustomAdapter 填充。问题是 ListView 不可见,如果我尝试填充列表应用程序崩溃!谢谢大家!!

这是UserCustomAdapter.java

public class UserCustomAdapter extends ArrayAdapter<User> {
 private static final int INVISIBLE = 4;
 private static final int VISIBLE = 0;
Context context;
 int layoutResourceId;
 ArrayList<User> data = new ArrayList<User>();

 public UserCustomAdapter(Context context, int layoutResourceId,  ArrayList<User> data) {
  super(context, layoutResourceId, data);

  this.layoutResourceId = layoutResourceId;
  this.context = context;
  this.data = data;
 }



 @Override
 public View getView(int position, View convertView, ViewGroup parent) {
      View row = convertView;
      UserHolder holder = null;

      System.out.println("@@@-getView-@@@");
      if (row == null) {
       LayoutInflater inflater = ((Activity) context).getLayoutInflater();
       row = inflater.inflate(layoutResourceId, parent, false);
       holder = new UserHolder();
       holder.textName = (TextView) row.findViewById(R.id.tv_prodotto);
       holder.textQta = (TextView) row.findViewById(R.id.tv_qta);
       //holder.textLocation = (TextView) row.findViewById(R.id.textView3);
       holder.btnEdit = (ImageButton) row.findViewById(R.id.button1);
       holder.btnDelete = (ImageButton) row.findViewById(R.id.button2);

       row.setTag(holder);
      } else {
       holder = (UserHolder) row.getTag();
      }

      User user = data.get(position);
      holder.Useritem = data.get(position);
      holder.textName.setText(user.getName());
      holder.textQta.setText(user.getAddress());
      //holder.textLocation.setText(user.getLocation());

      holder.btnDelete.setTag(holder.Useritem);// mi segno la posizione in modo da recuperarla poi in seguito!!
      holder.btnEdit.setTag(holder.Useritem);// mi segno la posizione in modo da recuperarla poi in seguito!!

      //rendo invisibili i pulsanti per la prima riga
      if(position == 0){
          holder.btnDelete.setVisibility(INVISIBLE);
          holder.btnEdit.setVisibility(INVISIBLE);
      }else{
          holder.btnDelete.setVisibility(VISIBLE);
          holder.btnEdit.setVisibility(VISIBLE);
      }

  holder.btnDelete.setOnClickListener(new OnClickListener() {
   @Override
   public void onClick(View v) {
        // TODO Auto-generated method stub
        Log.i("Delete Button Clicked", "**********");
        Toast.makeText(context, "Delete button Clicked",
          Toast.LENGTH_LONG).show();

        User itemToRemove = (User)v.getTag();
        Sector1.userAdapter.remove(itemToRemove);
        Sector1.userAdapter.notifyDataSetChanged();
   }
  });

      return row;
 }

 static class UserHolder {
  TextView textName;
  TextView textQta;
  //TextView textLocation;
  ImageButton btnEdit;
  ImageButton btnDelete;
  User Useritem;
 }

这是Sector1.java

public class Sector1 extends Fragment
{
    private Button btnNew_order,btnAggiungi;
    private Spinner spin_prodotto, spin_tipo;
    private EditText EtQta;
    ListView userList;
    Static UserCustomAdapter userAdapter;
    ArrayList<User> userArray = new ArrayList<User>();

        @Override
        public View onCreateView(LayoutInflater inflater, 
                ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.sector1, container, false);
            userAdapter = new UserCustomAdapter(getActivity().getBaseContext(), R.layout.row, userArray);
            userList = (ListView) rootView.findViewById(R.id.listView);
            userList.setItemsCanFocus(false);
            userList.setAdapter(userAdapter);   
            //userAdapter.setListAdapter();
            //userList.setListAdapter(userAdapter);
            //userAdapter.getView(0, rootView, container);


            spin_prodotto = (Spinner) rootView.findViewById(R.id.spin_prodotto);
            spin_tipo = (Spinner) rootView.findViewById(R.id.spin_tipo);
            btnNew_order = (Button) rootView.findViewById(R.id.btn_new_order);
            btnAggiungi = (Button) rootView.findViewById(R.id.btn_aggiungi);
            EtQta = (EditText) rootView.findViewById(R.id.Et_qta);

            btnAggiungi.setEnabled(false);

            btnNew_order.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    btnAggiungi.setEnabled(true);

                    Date now = new Date();
                    SimpleDateFormat DesiredFormat = new SimpleDateFormat("dd/MM/yyyy kk:MM");
                    String newFormat = DesiredFormat.format(now.getTime());

                    String Order = "Ordine del:\n" +newFormat;
//                  userAdapter.add(new User(Order, "Fornitore: Passerini"));           
//                  userAdapter.notifyDataSetChanged();         
                }       
            });         


            //return super.onCreateView(inflater, container, savedInstanceState);
             return rootView;
        }
    public void removeItemClickHandler(final View v) {
      User itemToRemove = (User)v.getTag();
      userAdapter.remove(itemToRemove);
      userAdapter.notifyDataSetChanged();
    }

}

这是我的扇区 1.xml

<FrameLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <LinearLayout
        android:id="@+id/LinearLayout1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <Button
            android:id="@+id/btn_new_order"
            style="?android:attr/buttonStyleSmall"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"            
            android:text="@string/new_order" />
    </LinearLayout>
    <LinearLayout
        android:id="@+id/LinearLayout2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="50dp"
        android:orientation="horizontal" >

        <Spinner
            android:id="@+id/spin_prodotto"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:entries="@array/passerini_product"
            android:prompt="@string/product_prompt"/>
    </LinearLayout>

    <LinearLayout
        android:id="@+id/LinearLayout3"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="120dp"
        android:orientation="horizontal" >

        <TextView
            android:id="@+id/lb_tv_qta"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="10sp"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:text="qta:" />

        <EditText
            android:id="@+id/Et_qta"
            android:layout_width="50dp"
            android:layout_height="wrap_content"
            android:layout_marginLeft="3dp"
            android:ems="2"
            android:inputType="numberSigned|numberDecimal"
            android:text="1" >
            <requestFocus />
        </EditText>      

        <Spinner
            android:id="@+id/spin_tipo"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_marginLeft="3dp"
            android:layout_weight="50"
            android:entries="@array/type_product" />

        <Button
            android:id="@+id/btn_aggiungi"
            style="?android:attr/buttonStyleSmall"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:drawableLeft="@android:drawable/ic_input_add"
            android:text="Aggiungi" />
    </LinearLayout> 

    <LinearLayout
        android:id="@+id/LinearLayout5"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="170dp"
        android:background="#ccffcc"
        android:orientation="horizontal" >

        <ListView

            android:id="@+id/listView"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content">           
<!--                tools:listitem="@layout/row"> -->           
        </ListView>
    </LinearLayout>
</FrameLayout>

这是row.xml

<RelativeLayout 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:padding="5dp"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/tv_prodotto"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="50dp"
        android:text="Prodotto"
        android:textStyle="bold" android:textColor="#000000" />

    <ImageButton
        android:id="@+id/button2"
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:focusable="false"
        android:focusableInTouchMode="false"
        android:src="@android:drawable/ic_menu_delete"     
        android:textColor="#0099CC" />

</RelativeLayout>

这个 id 我的MainActivity.java

    public class MainActivity extends FragmentActivity implements ActionBar.TabListener {

        AppSectionsPagerAdapter mAppSectionsPagerAdapter;  
        ViewPager mViewPager;

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

    // Settare il tipo di navigazione
            mAppSectionsPagerAdapter = new AppSectionsPagerAdapter(getSupportFragmentManager());
            final ActionBar actionBar = getActionBar();

            actionBar.setHomeButtonEnabled(false);
            actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

            mViewPager = (ViewPager) findViewById(R.id.pager);
            mViewPager.setAdapter(mAppSectionsPagerAdapter);
            mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
                @Override
                public void onPageSelected(int position) {
                            actionBar.setSelectedNavigationItem(position);
                }
            });

            // creo icona e scritta per il primo Tab
            Tab tab = actionBar.newTab()
                    .setText("Ordine")
                    .setTabListener(this)
                    .setIcon(R.drawable.computer);
            actionBar.addTab(tab);

            // creo icona e scritta per il primo Tab
            tab = actionBar.newTab()
                    .setText("Invio")
                    .setTabListener(this)
                    .setIcon(R.drawable.email);
            actionBar.addTab(tab);
        }



//public void removeItemClickHandler(final View v) {
//    User itemToRemove = (User)v.getTag();
//    userAdapter.remove(itemToRemove);
//    userAdapter.notifyDataSetChanged();
//  }  


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

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

            mViewPager.setCurrentItem(tab.getPosition());
        }

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


        public class AppSectionsPagerAdapter extends FragmentPagerAdapter {

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

    // Il return new chiama le altre classi (i Fragment) 
            @Override
            public Fragment getItem(int i) {
                switch (i) {
                    case 0:                      
                        return new Sector1();
                    case 1:
                        return new Sector2();

                    default:                       
                        Fragment fragment = new Sector1();
                        Bundle args = new Bundle();

                        fragment.setArguments(args);
                        return fragment;
                }
            }

    // Settare il titolo dei Sector

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

            public CharSequence getPageTitle(int position) {
                String tabLabel = null;
                switch (position) {

                case 0:
                tabLabel = getString(R.string.title_section1);
                break;

                case 1:
                tabLabel = getString(R.string.title_section2);
                break;              
                }   
                return tabLabel;
            }
        }
    }
4

1 回答 1

3

代替

LayoutInflater inflater = ((Activity) context).getLayoutInflater();  

LayoutInflater.from(context);  

在您的 UserAdapter.getView() 方法中。

始终查看您的日志 - 在大多数情况下,确定崩溃原因很有用。你有 ClassCastException 我认为这是不言自明的。您尝试在创建适配器时将适配器属性上下文转换为 Activity(适配器的第 43 行),同时将 getActivity().getBaseContext() 传递给适配器。

于 2013-09-22T16:43:30.937 回答