web-dev-qa-db-ja.com

リストビューにアイテムを追加-Android

これはAndroidでの初めての経験です。 ListViewにアイテムを追加しようとしています。私はタブを使用しますが、アイテムが追加されたことを確認する唯一の方法は、タブを変更してから最初のタブに戻ることです。

私はあちこち探しましたが、いつも見つけました

adapter.notifyDataSetChanged();

しかし、私にはうまくいきません。

先ほど言ったように、固定タブ+スワイプでプロジェクトを作成しました。行にEditText、Spinner、およびButtonがあるリストビューが必要です。タブに使用されるフラグメントの下部に、ImageButtonがあります。クリックして、新しい行を作成します。

私のカスタムアダプタ:

package com.andreapivetta.uconverter;

import Java.util.ArrayList;

import Android.content.Context;
import Android.view.LayoutInflater;
import Android.view.View;
import Android.view.ViewGroup;
import Android.widget.ArrayAdapter;

public class CustomAdapter extends ArrayAdapter<String> {
private final Context context;
private final int resourceID;

    public CustomAdapter(Context context, int resource, ArrayList<String> bah) {
        super(context, resource, bah);

        this.context = context;
        this.resourceID = resource;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View rowView = inflater.inflate(resourceID, parent, false);

        return rowView;
    }
}

fragment_main_dummy.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:paddingBottom="@dimen/activity_vertical_margin"
Android:paddingLeft="@dimen/activity_horizontal_margin"
Android:paddingRight="@dimen/activity_horizontal_margin"
Android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity$DummySectionFragment" >

<ListView
    Android:id="@+id/unitListView"
    Android:layout_width="match_parent"
    Android:layout_height="wrap_content" >
</ListView>

<ImageButton
    Android:id="@+id/moreImageButton"
    Android:layout_width="wrap_content"
    Android:layout_height="wrap_content"

    Android:layout_alignParentBottom="true"
    Android:layout_alignParentRight="true"

    Android:contentDescription="@string/image_button_delete"
    Android:src="@Android:drawable/ic_input_add" />

</RelativeLayout>

Row.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:Android="http://schemas.Android.com/apk/res/Android"
            Android:layout_width="match_parent"
            Android:layout_height="match_parent">

<TextView
    Android:id="@+id/textView1"
    Android:layout_width="wrap_content"
    Android:layout_height="wrap_content"
    Android:layout_alignParentLeft="true"
    Android:layout_alignParentTop="true" />

<EditText
    Android:id="@+id/unitEditText"
    Android:layout_width="wrap_content"
    Android:layout_height="wrap_content"
    Android:layout_alignParentLeft="true"
    Android:layout_below="@+id/textView1"
    Android:ems="10"
    Android:inputType="numberDecimal" >

    <requestFocus />
</EditText>

<Spinner
    Android:id="@+id/unitSpinner"
    Android:layout_width="wrap_content"
    Android:layout_height="wrap_content"
    Android:layout_alignBottom="@+id/imageButton1"
    Android:layout_marginBottom="15dp"
    Android:layout_toRightOf="@+id/unitEditText" />

<ImageButton
    Android:id="@+id/imageButton1"
    Android:layout_width="wrap_content"
    Android:layout_height="wrap_content"
    Android:layout_alignBottom="@+id/unitEditText"
    Android:layout_alignParentRight="true"

    Android:onClick="removeItem"

    Android:contentDescription="@string/image_button_delete"
    Android:src="@Android:drawable/ic_menu_delete" />

</RelativeLayout>

主な活動...

public class MainActivity 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
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Set up the action bar.
    final ActionBar actionBar = getActionBar();
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

    // 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 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 callback (listener) for when
        // this tab is selected.
        actionBar.addTab(actionBar.newTab()
                .setText(mSectionsPagerAdapter.getPageTitle(i))
                .setTabListener(this));
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@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 onTabUnselected(ActionBar.Tab tab,
        FragmentTransaction fragmentTransaction) {
}

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

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

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

    @Override
    public Fragment getItem(int position) {
        // getItem is called to instantiate the fragment for the given page.
        // Return a DummySectionFragment (defined as a static inner class
        // below) with the page number as its lone argument.
        Fragment fragment = new DummySectionFragment();
        Bundle args = new Bundle();
        args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public int getCount() {
        // Show 4 total pages.
        return 4;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        Locale l = Locale.getDefault();
        switch (position) {
        case 0:
            return getString(R.string.title_section1).toUpperCase(l);
        case 1:
            return getString(R.string.title_section2).toUpperCase(l);
        case 2:
            return getString(R.string.title_section3).toUpperCase(l);
        case 3:
            return getString(R.string.title_section4).toUpperCase(l);
        }
        return null;
    }
}

/**
 * A dummy fragment representing a section of the app, but that simply
 * displays dummy text.
 */
public static class DummySectionFragment extends Fragment {
    /**
     * The fragment argument representing the section number for this
     * fragment.
     */
    ArrayList<String> myStringArray1 =  new ArrayList<String>();//new String[]{"Egzo","Eg","Egzona"};
    String[] myStringArray2 = new String[]{"aaa","bbb","ccc"};
    String[] myStringArray3 = new String[]{"ddd","eeee"};
    String[] myStringArray4 = new String[]{"Cia","ci","Ciao"};
    public static ArrayAdapter<String> adapter;

    public static final String ARG_SECTION_NUMBER = "section_number";

    public DummySectionFragment() {
    }

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

        // ListView
        ListView unitListView = (ListView) rootView.findViewById(R.id.unitListView);

        switch(getArguments().getInt(ARG_SECTION_NUMBER)) {
        case 1:
            myStringArray1.add("mmm");

            adapter = new CustomAdapter(getActivity(), R.layout.row, myStringArray1);
            unitListView.setAdapter(adapter);
            break;
        case 2:
            adapter = new ArrayAdapter<String>(getActivity(), R.layout.row, R.id.textView1, myStringArray2);
            unitListView.setAdapter(adapter);
            break;
        case 3:
            adapter = new ArrayAdapter<String>(getActivity(), R.layout.row, R.id.textView1, myStringArray3);
            unitListView.setAdapter(adapter);
            break;
        case 4:
            adapter = new ArrayAdapter<String>(getActivity(), R.layout.row, R.id.textView1, myStringArray4);
            unitListView.setAdapter(adapter);
            break;
        }
        unitListView.setOnItemClickListener(listViewOnClickListener);

        // ImageButton
        ImageButton moreImageButton = (ImageButton) rootView.findViewById(R.id.moreImageButton);
        moreImageButton.setOnClickListener(moreListener);


        return rootView;
    }

    public OnClickListener moreListener = new OnClickListener(){

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            myStringArray1.add("Andrea");
            adapter.clear();
            adapter.addAll(myStringArray1);
            adapter.notifyDataSetChanged();
        }

    };

    public OnItemClickListener listViewOnClickListener = new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                long arg3) {
            // TODO Auto-generated method stub

        }

    };
}

}

現在、最初のタブでのみ作業していることに注意してください...

何が間違っていますか? :)

17
andrew
ListView myListView = (ListView) rootView.findViewById(R.id.myListView);
ArrayList<String> myStringArray1 = new ArrayList<String>();
myStringArray1.add("something");
adapter = new CustomAdapter(getActivity(), R.layout.row, myStringArray1);
myListView.setAdapter(adapter);

このようにしてみてください

public OnClickListener moreListener = new OnClickListener() {

    @Override
    public void onClick(View v) {
        adapter = null;
        myStringArray1.add("Andrea");
        adapter = new CustomAdapter(getActivity(), R.layout.row, myStringArray1);
        myListView.setAdapter(adapter);
        adapter.notifyDataSetChanged();
    }       
};
27
Amit Gupta

これを試してみてください

public class Third extends ListActivity {
private ArrayAdapter<String> adapter;
private List<String> liste;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_third);
     String[] values = new String[] { "Android", "iPhone", "WindowsMobile",
                "Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X",
                "Linux", "OS/2" };
     liste = new ArrayList<String>();
     Collections.addAll(liste, values);
     adapter = new ArrayAdapter<String>(this,
                Android.R.layout.simple_list_item_1, liste);
     setListAdapter(adapter);
}
 @Override
  protected void onListItemClick(ListView l, View v, int position, long id) {
     liste.add("Nokia");
     adapter.notifyDataSetChanged();
  }
}
3