从按钮 OnClick 方法中访问 listview/arrayadapter

Posted

技术标签:

【中文标题】从按钮 OnClick 方法中访问 listview/arrayadapter【英文标题】:Accessing listview/arrayadapter from within button OnClick method 【发布时间】:2014-12-27 07:25:34 【问题描述】:

这可能是一个有点愚蠢的问题,但我很难理解如何引用我创建的列表视图/适配器。我首先创建了一个自定义列表视图,它允许我显示其中包含图片和文本的列表项。我在网上找到了很多很棒的教程,所以这部分还不错。然后我在列表视图的底部添加了两个按钮,我想用它们来操作列表视图中的数据。现在我可以弄清楚当我在列表的onItemClickListener 中时如何访问该列表,因为您只需调用parent.getItemAtPosition(position) 即可访问它。我不太确定如何在按钮的onClick 方法中访问此列表,因为父/位置不作为参数传递。所以我想我的第一个问题是......

    如何正确访问我在按钮onClick 方法中创建的列表视图/数组适配器。

我一直在努力解决的另一个问题是如何通过搜索包含该行的特定元素的值来在我的列表视图中搜索一个项目(行)。例如,在下面的代码中,我创建的行有五个图像、两个文本字段和一个布尔值。那么我将如何在我的列表中搜索以找到“地址”为 555555 的行,该行对应于 Harley Davidson 列表条目。

我在下面包含了我的代码。非常感谢您的帮助。

HelmetList.java

public class HelmetList

    public HelmetList (String name, String address, String img_hel, String img_rec, String img_bat,
                            String img_dsk, String img_str, Boolean selected)
    
        super();
        this.name       = name;
        this.address    = address;
        this.img_hel    = img_hel;
        this.img_rec    = img_rec;
        this.img_bat    = img_bat;
        this.img_dsk    = img_dsk;
        this.img_str    = img_str;
        this.selected   = selected;
    

    private String name;
    private String address;
    private String img_hel;
    private String img_rec;
    private String img_bat;
    private String img_dsk;
    private String img_str;
    private Boolean selected;

    public String getName ()
    
        return name;
    

    public void setName (String s_name)
    
        this.name = s_name;
    

    public String getAddress ()
    
        return address;
    

    public void setAddress (String s_address)
    
        this.address = s_address;
    

    public String getImgHel ()
    
        return img_hel;
    

    public void setImgHel (String s_img_hel)
    
        this.img_hel = s_img_hel;
    

    public String getImgRec ()
    
        return img_rec;
    

    public void setImgRec (String s_img_rec)
    
        this.img_rec = s_img_rec;
    

    public String getImgBat ()
    
        return img_bat;
    

    public void setImgBat (String s_img_bat)
    
        this.img_bat = s_img_bat;
    

    public String getImgDsk ()
    
        return img_dsk;
    

    public void setImgDsk (String s_img_dsk)
    
        this.img_dsk = s_img_dsk;
    

    public String getImgStr ()
    
        return img_str;
    

    public void setImgStr (String s_img_str)
    
        this.img_str = s_img_str;
    

    public Boolean getSelected ()
    
        return selected;
    

    public void setSelected (Boolean s_selected)
    
        this.selected = s_selected;
    

HelmetListAdapter.java

public class HelmetListAdapter extends ArrayAdapter<HelmetList>

    private int resource;
    private LayoutInflater inflater;
    private Context context;

    public HelmetListAdapter (Context p_context, int p_resource, List<HelmetList> p_objects)
    
        super (p_context, p_resource, p_objects);
        resource = p_resource;
        inflater = LayoutInflater.from (p_context);
        context = p_context;
    

    @Override
    public View getView (int position, View convertView, ViewGroup parent)
    
        convertView = ( RelativeLayout ) inflater.inflate( resource, null );
        HelmetList Helmet = getItem (position);

        TextView hname = (TextView) convertView.findViewById(R.id.h_name);
        hname.setText(Helmet.getName ());

        TextView haddress = (TextView) convertView.findViewById(R.id.h_address);
        haddress.setText(Helmet.getAddress ());

        ImageView himage = (ImageView) convertView.findViewById(R.id.h_image);
        String uri = "drawable/" + Helmet.getImgHel();
        int imageResource = context.getResources().getIdentifier(uri, null, context.getPackageName());
        Drawable image = context.getResources().getDrawable(imageResource);
        himage.setImageDrawable(image);

        ImageView hrec = (ImageView) convertView.findViewById(R.id.h_rec);
        uri = "drawable/" + Helmet.getImgRec();
        imageResource = context.getResources().getIdentifier(uri, null, context.getPackageName());
        image = context.getResources().getDrawable(imageResource);
        hrec.setImageDrawable(image);

        ImageView hlbat = (ImageView) convertView.findViewById(R.id.h_lb);
        uri = "drawable/" + Helmet.getImgBat();
        imageResource = context.getResources().getIdentifier(uri, null, context.getPackageName());
        image = context.getResources().getDrawable(imageResource);
        hlbat.setImageDrawable(image);

        ImageView hldsk = (ImageView) convertView.findViewById(R.id.h_ld);
        uri = "drawable/" + Helmet.getImgDsk();
        imageResource = context.getResources().getIdentifier(uri, null, context.getPackageName());
        image = context.getResources().getDrawable(imageResource);
        hldsk.setImageDrawable(image);

        ImageView hstr = (ImageView) convertView.findViewById(R.id.h_str);
        uri = "drawable/" + Helmet.getImgStr();
        imageResource = context.getResources().getIdentifier(uri, null, context.getPackageName());
        image = context.getResources().getDrawable(imageResource);
        hstr.setImageDrawable(image);

        return convertView;

    

MainActivity.java

public class MainActivity extends Activity

    private ListView lvhelmets;
    private HelmetListAdapter adhelmets;
    private Context ctx;
    List<Integer> selected;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ctx = this;

        List<HelmetList> helmetlist = new ArrayList<HelmetList>();
        helmetlist.add(new HelmetList("Bell", "11111", "helmetpic0", "rec",
                "bat", "mm", "str", Boolean.FALSE));
        helmetlist.add(new HelmetList("Shoei", "33333", "helmetpic1", "rec",
                                        "bat", "mm", "str", Boolean.FALSE));
        helmetlist.add(new HelmetList("Harley Davidson", "55555", "helmetpic2", "rec",
                                        "bat", "mm", "str", Boolean.FALSE));
        helmetlist.add(new HelmetList("Joe Rocket", "77777", "helmetpic3", "rec",
                "bat", "mm", "str", Boolean.FALSE));


        lvhelmets = (ListView) findViewById(R.id.Helmet_list);
        lvhelmets.setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE);

        adhelmets = new HelmetListAdapter(ctx, R.layout.row_format, helmetlist);
        lvhelmets.setAdapter (adhelmets);

        Button price = (Button) findViewById(R.id.bPrice);
        Button safety = (Button) findViewById(R.id.bSafety);

        price.setOnClickListener(new View.OnClickListener()
        
            @Override
            public void onClick(View view)
            
                Toast.makeText(MainActivity.this, "price", Toast.LENGTH_SHORT).show();
            
        );

        safety.setOnClickListener(new View.OnClickListener()
        
            @Override
            public void onClick(View view)
            
                Toast.makeText(MainActivity.this, "safety", Toast.LENGTH_SHORT).show();
            
        );



        lvhelmets.setOnItemClickListener(new OnItemClickListener()
        
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id)
            
                HelmetList helmet = (HelmetList) parent.getItemAtPosition(position);

                if (!helmet.getSelected())
                
                    view.setBackgroundColor(Color.LTGRAY);
                    helmet.setSelected(Boolean.TRUE);
                
                else
                
                    view.setBackgroundColor(Color.TRANSPARENT);
                    helmet.setSelected(Boolean.FALSE);
                
            
        );

    


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

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_
    android:layout_
    android:orientation="vertical" >

    <ListView
        android:id="@+id/Helmet_list"
        android:layout_
        android:layout_
        android:paddingTop="5dp"
        android:choiceMode="multipleChoice"
        android:layout_weight="1">
    </ListView>

    <LinearLayout
        android:id="@+id/btnHolderLL"
        android:layout_
        android:layout_
        android:orientation="horizontal" >

        <Button
            android:id="@+id/bPrice"
            android:layout_
            android:layout_
            android:layout_weight="1"
            android:paddingRight="1dp"
            android:paddingLeft="1dp"
            android:textColor="#FFFFFF"
            android:background="#222222"
            android:text="Price"
            android:clickable="true" />

        <Button
            android:id="@+id/bSafety"
            android:layout_
            android:layout_
            android:layout_weight="1"
            android:paddingRight="1dp"
            android:paddingLeft="1dp"
            android:textColor="#FFFFFF"
            android:background="#222222"
            android:text="Safety"
            android:clickable="true" />
    </LinearLayout>

</LinearLayout>

row_format.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_
    android:layout_
    android:orientation="horizontal"
    android:padding="5dip" >

    <!--  ListRow Left side Thumbnail image -->
    <LinearLayout android:id="@+id/thumbnail"
        android:layout_
        android:layout_
        android:padding="3dip"
        android:layout_alignParentLeft="true"
        android:layout_marginRight="5dip">
        <ImageView
            android:id="@+id/h_image"
            android:layout_
            android:layout_
            android:layout_marginLeft="5dip"/>
    </LinearLayout>

    <TextView
        android:id="@+id/h_name"
        android:layout_
        android:layout_
        android:layout_alignTop="@+id/thumbnail"
        android:layout_toRightOf="@+id/thumbnail"
        android:textColor="#040404"
        android:typeface="sans"
        android:textSize="20dip"
        android:layout_marginTop="5dip"
        android:textStyle="bold"/>

    <TextView
        android:id="@+id/h_address"
        android:layout_
        android:layout_
        android:layout_below="@id/h_name"
        android:textColor="#343434"
        android:textSize="12dip"
        android:layout_marginTop="1dip"
        android:layout_toRightOf="@+id/thumbnail"  />

    <ImageView
        android:id="@+id/h_rec"
        android:layout_
        android:layout_
        android:layout_alignParentRight="true"
        android:layout_marginRight="5dp"
        android:layout_centerVertical="true" />

    <ImageView
        android:id="@+id/h_lb"
        android:layout_
        android:layout_
        android:layout_alignParentRight="true"
        android:layout_marginRight="45dp"
        android:layout_centerVertical="true" />

    <ImageView
        android:id="@+id/h_ld"
        android:layout_
        android:layout_
        android:layout_alignParentRight="true"
        android:layout_marginRight="85dp"
        android:layout_centerVertical="true" />

    <ImageView
        android:id="@+id/h_str"
        android:layout_
        android:layout_
        android:layout_alignParentRight="true"
        android:layout_marginRight="125dp"
        android:layout_centerVertical="true" />
</RelativeLayout>

【问题讨论】:

【参考方案1】:

onClick 方法中,尝试:

lvhelmets.setAdapter(new HelmetListAdapter(ctx, rowf_format.xml, helmetList));

这将调用您的适配器,该适配器将填充listview

【讨论】:

好的,我知道了。现在我如何去访问一个实际的行?例如,我将如何为特定行执行.setSelected(Boolean.TRUE) 好吧,没关系愚蠢的问题,我想通了 -> HelmetList helmet = (HelmetList) lvhelmets.getItemAtPosition(0);... 但这会导致一些奇怪的行为。从上面的代码中可以看出,我只是更改了行的背景,然后调用setSelected(Boolean.TRUE); 来注意选择了一行。当我从按钮onClick 中修改行属性时,灰色行突出显示消失。您知道为什么会这样吗?【参考方案2】:

如果整数列表用于保存所选项目的索引,则在您的 ListViews onItemClicked 侦听器中,在选择一个时将该位置添加到您的整数列表中。

使您的 HelmetLists 列表成为您的 Activity 中的一个字段。这样,当您按下两个按钮中的任何一个时,您将拥有所需的 HelmetList 的索引以及可以从中检索每个对象的列表。不确定您是否允许多选。

【讨论】:

以上是关于从按钮 OnClick 方法中访问 listview/arrayadapter的主要内容,如果未能解决你的问题,请参考以下文章

button按钮如何在onclick中调用java后台函数

从 html5 按钮 onclick 事件调用服务器端方法

Unity UI按钮不调用Onclick方法

带有onclick按钮的vb访问子表单

从 onclick 事件访问组合框中的选定值

js 动态添加的按钮 onclick事件怎么写?