当前位置: 首页 > 面试题库 >

将项目添加到ListView-Android

王嘉木
2023-03-14
问题内容

这是我第一次接触android。我正在尝试向我的ListView添加项目。我使用“选项卡”,查看添加项目的唯一方法是更改​​选项卡,然后返回到第一个选项卡。

我到处搜寻,而且一直都找到

adapter.notifyDataSetChanged();

但对我不起作用。

正如我所说,我已经使用固定标签+滑动创建了项目。我只希望有一个列表视图,哪些行具有一个EditText,一个Spinner和一个Button。在用于选项卡的Fragment的底部,我有一个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>

行.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

        }

    };
}

}

请注意,我现在仅使用第一个标签…

我究竟做错了什么?:)


问题答案:
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();
    }       
};


 类似资料:
  • 我想创建一个列表视图,只能通过鼠标进行多项选择(不按住ctrl或Shift) 单击某个项目应选择此项目。如果选择了其他项目,请将此新项目添加到所选列表中。以前选中此项目时,请取消选中它。 我不想保留选定的项目。selectionModel上有一个名为“selectIndices()”的方法,它只接受一个或多个整数,而不是整数列表。。。 有男孩有主意吗?

  • 本文向大家介绍将Bootstrap添加到React.js项目,包括了将Bootstrap添加到React.js项目的使用技巧和注意事项,需要的朋友参考一下 有多种方法可以在react项目中添加引导程序。 使用引导CDN 安装引导程序依赖项 使用React Bootstrap软件包 使用引导CDN 这是添加引导程序的最简单方法。与其他CDN一样,我们可以在react项目的index.html中添加引

  • 在我的activity_main.xml我有这个工具栏: 在清单中有

  • 问题内容: 我将此组合框添加到面板中。如果直接在数据库中添加一些项目,则希望那些新添加的项目显示在组合框中。 我可以在调试时看到这些值,但是这些值不会出现在我的组合框中。 如何在不关闭面板的情况下将那些新添加的值放入组合框? 问题答案: 如何使用ComboBoxModel?像这样…

  • 我目前正在开发一个C#WPF应用程序,我试图在其中添加一个图像,然后在每个列表项中添加一些文本。 我已经为文本工作的绑定,但图像不显示。 下面是我的XAML: 下面是我的Directory清单类 下面是我如何添加项目到列表框 文字添加得很好,但图像没有。 我不确定这是否相关,但我在VS2010的控制台输出中看到以下内容 系统。Windows.Data错误:4:找不到引用为“RelativeSour

  • 如果你打算使用 扩展来添加附加功能,那么还可以运行以下命令: