项目添加到ListView控件 - 机器人控件、机器人、项目、ListView

2023-09-12 09:17:06 作者:涐想谈一场永不分手的恋爱

这是我与Android第一次经历。我试图将项目添加到我的ListView。 我使用的标签,而只有这样,才能看到加入该项目是改变选项卡,然后再回到第一个标签。

我,四处搜寻,我总是发现

  adapter.notifyDataSetChanged();
 

但对我不起作用。

我创建的项目,正如我所说的,固定选项卡+刷卡。 我只是想有列表视图该行有一个EditText,一个微调和一个按钮。 在使用该选项卡的片段的底部,我有一个ImageButton的。我想一下就可以了,并有一个新行。

我的自定义适配器:

 包com.andreapivetta.uconverter;

进口的java.util.ArrayList;

进口android.content.Context;
进口android.view.LayoutInflater;
进口android.view.View;
进口android.view.ViewGroup;
进口android.widget.ArrayAdapter;

公共类CustomAdapter扩展ArrayAdapter<字符串> {
私人最终上下文的背景下;
私人最终诠释RESOURCEID;

    公共CustomAdapter(上下文的背景下,INT资源的ArrayList<字符串> BAH){
        超(背景下,资源,呸);

        this.context =背景;
        this.resourceID =资源;
    }

    @覆盖
    公共查看getView(INT位置,查看convertView,ViewGroup中父){
        LayoutInflater充气=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        查看rowView = inflater.inflate(RESOURCEID,父母,假);

        返回rowView;
    }
}
 
WPF 数据集合绑定到DataGrid ListView或者其他列表控件

fragment_main_dummy.xml

 < RelativeLayout的的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
的xmlns:工具=htt​​p://schemas.android.com/tool​​s
机器人:layout_width =match_parent
机器人:layout_height =match_parent
机器人:paddingBottom会=@扪/ activity_vertical_margin
机器人:以下属性来=@扪/ activity_horizo​​ntal_margin
机器人:paddingRight =@扪/ activity_horizo​​ntal_margin
机器人:paddingTop =@扪/ activity_vertical_margin
工具:上下文=MainActivity $ DummySectionFragment。>

<的ListView
    机器人:ID =@ + ID / unitListView
    机器人:layout_width =match_parent
    机器人:layout_height =WRAP_CONTENT>
< / ListView控件>

<的ImageButton
    机器人:ID =@ + ID / moreImageButton
    机器人:layout_width =WRAP_CONTENT
    机器人:layout_height =WRAP_CONTENT

    机器人:layout_alignParentBottom =真
    机器人:layout_alignParentRight =真

    机器人:contentDescription =@字符串/ image_button_delete
    机器人:SRC =@机器人:可绘制/ ic_input_add/>

< / RelativeLayout的>
 

Row.xml

 < XML版本=1.0编码=UTF-8&GT?;
< RelativeLayout的的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
            机器人:layout_width =match_parent
            机器人:layout_height =match_parent>

<的TextView
    机器人:ID =@ + ID / textView1
    机器人:layout_width =WRAP_CONTENT
    机器人:layout_height =WRAP_CONTENT
    机器人:layout_alignParentLeft =真
    机器人:layout_alignParentTop =真/>

<的EditText
    机器人:ID =@ + ID / unitEditText
    机器人:layout_width =WRAP_CONTENT
    机器人:layout_height =WRAP_CONTENT
    机器人:layout_alignParentLeft =真
    机器人:layout_below =@ + ID / textView1
    机器人:EMS =10
    机器人:inputType =numberDecimal>

    <不是requestFocus />
< /的EditText>

<微调
    机器人:ID =@ + ID / unitSpinner
    机器人:layout_width =WRAP_CONTENT
    机器人:layout_height =WRAP_CONTENT
    机器人:layout_alignBottom =@ + ID / imageButton1
    机器人:layout_marginBottom =15dp
    机器人:layout_toRightOf =@ + ID / unitEditText/>

<的ImageButton
    机器人:ID =@ + ID / imageButton1
    机器人:layout_width =WRAP_CONTENT
    机器人:layout_height =WRAP_CONTENT
    机器人:layout_alignBottom =@ + ID / unitEditText
    机器人:layout_alignParentRight =真

    机器人:的onClick =为removeItem

    机器人:contentDescription =@字符串/ image_button_delete
    机器人:SRC =@机器人:可绘制/ ic_menu_delete/>

< / RelativeLayout的>
 

MainActivity ...

 公共类MainActivity扩展FragmentActivity工具
    ActionBar.TabListener {

/ **
 *在{@link android.support.v4.view.PagerAdapter},将提供
 *对于每个部分的片段。我们使用
 * {@link android.support.v4.app.FragmentPagerAdapter}衍生物,它
 *将让每一个加载的片段记忆。如果这成为过记忆
 *密集,它可能是最好切换到
 * {@link android.support.v4.app.FragmentStatePagerAdapter}。
 * /
SectionsPagerAdapter mSectionsPagerAdapter;

/ **
 *在{@link ViewPager}将承载部分内容。
 * /
ViewPager mViewPager;


@覆盖
保护无效的onCreate(包savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.activity_main);

    //设置操作栏。
    最后的动作条动作条= getActionBar();
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

    //创建将返回一个片段为三个的适配器
    //应用程序的主要部分。
    mSectionsPagerAdapter =新SectionsPagerAdapter(getSupportFragmentManager());

    //设置的ViewPager与部分适配器。
    mViewPager =(ViewPager)findViewById(R.id.pager);
    mViewPager.setAdapter(mSectionsPagerAdapter);

    //当不同部分之间的刷卡,选择相应的
    //标签。我们也可以使用ActionBar.Tab#选择()要做到这一点,如果我们有
    //引用的标签。
    mViewPager
            .setOnPageChangeListener(新ViewPager.SimpleOnPageChangeListener(){
                @覆盖
                公共无效onPageSelected(INT位置){
                    actionBar.setSelectedNavigationItem(位置);
                }
            });

    //对于每个应用程序的章节中,添加一个标签,操作栏。
    的for(int i = 0; I< mSectionsPagerAdapter.getCount();我++){
        //创建与对应于由所定义的页标题文本标签
        //适配器。同时,指定此活动的对象,它实现
        //该TabListener界面,回调(监听程序)进行时
        //这个选项卡中选择。
        actionBar.addTab(actionBar.newTab()
                .setText(mSectionsPagerAdapter.getPageTitle(I))
                .setTabListener(本));
    }
}

@覆盖
公共布尔onCreateOptionsMenu(功能菜单){
    //充气菜单;这增加了项目操作栏,如果它是present。
    。getMenuInflater()膨胀(R.menu.main,菜单);
    返回true;
}

@覆盖
公共无效onTabSelected(ActionBar.Tab选项卡,
        FragmentTransaction fragmentTransaction){
    //当选择给定的标签,切换到对应页面
    //该ViewPager。
    mViewPager.setCurrentItem(tab.getPosition());
}

@覆盖
公共无效onTabUnselected(ActionBar.Tab选项卡,
        FragmentTransaction fragmentTransaction){
}

@覆盖
公共无效onTabReselected(ActionBar.Tab选项卡,
        FragmentTransaction fragmentTransaction){
}

/ **
 * A {@link FragmentPagerAdapter}返回对应的片段
 *章节/标签/页之一。
 * /
公共类SectionsPagerAdapter扩展FragmentPagerAdapter {

    公共SectionsPagerAdapter(FragmentManager FM){
        超(FM);
    }

    @覆盖
    公共片段的getItem(INT位置){
        //的getItem被称为实例化片段给定的页面。
        //返回一个DummySectionFragment(定义为静态内部类
        下图)与页面数量作为其唯一的参数//。
        片段片段=新DummySectionFragment();
        捆绑的args =新包();
        args.putInt(DummySectionFragment.ARG_SECTION_NUMBER,位置+ 1);
        fragment.setArguments(参数);
        返回片段;
    }

    @覆盖
    公众诠释getCount将(){
        //显示4总页数。
        返回4;
    }

    @覆盖
    公共CharSequence的getPageTitle(INT位置){
        区域设置L = Locale.getDefault();
        开关(位置){
        情况下0:
            返回的getString(R.string.title_section1).toUpperCase(升);
        情况1:
            返回的getString(R.string.title_section2).toUpperCase(升);
        案例2:
            返回的getString(R.string.title_section3).toUpperCase(升);
        案例3:
            返回的getString(R.string.title_section4).toUpperCase(升);
        }
        返回null;
    }
}

/ **
 *一个虚拟片段重新presenting应用程序的一部分,但只是
 *显示虚拟文本。
 * /
公共静态类DummySectionFragment扩展片段{
    / **
     *片段参数重新presenting本章节号
     * 分段。
     * /
    ArrayList的<字符串> myStringArray1 =新的ArrayList<字符串>(); //新的String [] {Egzo,例如,Egzona};
    的String [] myStringArray2 =新的String [] {AAA,BBB,CCC};
    的String [] myStringArray3 =新的String [] {DDD,EEEE};
    的String [] myStringArray4 =新的String [] {CIA,词,侨};
    公共静态ArrayAdapter<字符串>适配器;

    公共静态最后弦乐ARG_SECTION_NUMBER =section_number标;

    公共DummySectionFragment(){
    }

    @覆盖
    公共查看onCreateView(LayoutInflater充气,容器的ViewGroup,捆绑savedInstanceState){
        查看rootView = inflater.inflate(R.layout.fragment_main_dummy,集装箱,假);
        // TextView的dummyTextView =(TextView中)rootView.findViewById(R.id.section_label);
        //dummyTextView.setText(Integer.toString(getArguments().getInt(ARG_SECTION_NUMBER)));

        // 列表显示
        ListView控件unitListView =(ListView控件)rootView.findViewById(R.id.unitListView);

        开关(getArguments()。调用getInt(ARG_SECTION_NUMBER)){
        情况1:
            myStringArray1.add(MMM);

            适配器=新CustomAdapter(getActivity(),R.layout.row,myStringArray1);
            unitListView.setAdapter(适配器);
            打破;
        案例2:
            适配器=新的ArrayAdapter<字符串>(getActivity(),R.layout.row,R.id.textView1,myStringArray2);
            unitListView.setAdapter(适配器);
            打破;
        案例3:
            适配器=新的ArrayAdapter<字符串>(getActivity(),R.layout.row,R.id.textView1,myStringArray3);
            unitListView.setAdapter(适配器);
            打破;
        壳体4:
            适配器=新的ArrayAdapter<字符串>(getActivity(),R.layout.row,R.id.textView1,myStringArray4);
            unitListView.setAdapter(适配器);
            打破;
        }
        unitListView.setOnItemClickListener(listViewOnClickListener);

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


        返回rootView;
    }

    公共OnClickListener moreListener =新OnClickListener(){

        @覆盖
        公共无效的onClick(视图v){
            // TODO自动生成方法存根

            myStringArray1.add(安德烈);
            adapter.clear();
            adapter.addAll(myStringArray1);
            adapter.notifyDataSetChanged();
        }

    };

    公共OnItemClickListener listViewOnClickListener =新OnItemClickListener(){

        @覆盖
        公共无效onItemClick(适配器视图<>为arg0,查看ARG1,INT ARG2,
                长ARG3){
            // TODO自动生成方法存根

        }

    };
}

}
 

请注意,我只涉及到了第一个选项卡,现在...

我是什么做错了吗? :)

解决方案

 的ListView myListView =(ListView控件)rootView.findViewById(R.id.myListView);
ArrayList的<字符串> myStringArray1 =新的ArrayList<字符串>();
myStringArray1.add(东西);
适配器=新CustomAdapter(getActivity(),R.layout.row,myStringArray1);
myListView.setAdapter(适配器);
 

试试这样

 公共OnClickListener moreListener =新OnClickListener(){

    @覆盖
    公共无效的onClick(视图v){
        适配器= NULL;
        myStringArray1.add(安德烈);
        适配器=新CustomAdapter(getActivity(),R.layout.row,myStringArray1);
        myListView.setAdapter(适配器);
        adapter.notifyDataSetChanged();
    }
};
 

This is my first experience with android. I'm trying to add items to my ListView. I use Tabs, and the only way to see that the item was added is to change tab and then come back to the first tab.

I searched around, and I've always found

adapter.notifyDataSetChanged();

but doesn't work for me.

I have created the project with, as I said, Fixed Tabs + Swipe. I simply want to have listviews which rows have an EditText, a Spinner and a Button. On the bottom of the Fragment used for the tab, I have an ImageButton. I want to click on it and have a new Row.

my custom Adapter:

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>

MainActivity...

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

        }

    };
}

}

Note that I'm working only with the first tab right now...

What am I doing wrong? :)

解决方案

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);

Try it like this

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();
    }       
};