Android: AdapterView选择项目

huangapple go评论82阅读模式
英文:

Android: AdapterView select item

问题

I have an AdapterView filled with items Android: AdapterView选择项目 and I would like to select the item I click on, something like this: Android: AdapterView选择项目 is there a possible way I can do this?

This is how I build the adapter:

adapter = new ArrayAdapter<String>(
                            context,
                            android.R.layout.simple_selectable_list_item,
                            QuestionActivity.OptionArrayList.get(position));
                    context.startActivity(i);
英文:

I have an AdapterView filled with items Android: AdapterView选择项目

and I would like to select the item I click on, something like this:Android: AdapterView选择项目
is there a possible way I can do this?

This is how I build the adapter

adapter = new ArrayAdapter&lt;String&gt;(
                            context,
                            android.R.layout.simple_selectable_list_item,
                            QuestionActivity.OptionArrayList.get(position));
                    context.startActivity(i);

答案1

得分: 2

这是一个示例项目,其中设置了一个ListView的OnItemClickListener,当用户点击其中的项时,它会更改背景。代码已经很明了了,如果有问题,请随时提问。

MainActivity.java:

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import androidx.appcompat.app.AppCompatActivity;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity
{
    View lastChangedView = null;

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

        ArrayList<String> arrayList = new ArrayList<>();
        arrayList.add("One");
        arrayList.add("Two");
        arrayList.add("Three");

        final ArrayAdapter<String> adapter = new ArrayAdapter<>(
                this,
                R.layout.list_view_item,
                arrayList);

        ListView listView = findViewById(R.id.listView);
        listView.setAdapter(adapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener()
        {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id)
            {
                if (lastChangedView != null)
                {
                    lastChangedView.setBackgroundResource(R.drawable.normal_back);
                }
                lastChangedView = view;
                Log.d("Main", "Item click at " + position);
                view.setBackgroundResource(R.drawable.selected_back);
            }
        });
    }
}

acitivty_main.xml:

<FrameLayout 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"
    tools:context=".MainActivity">

    <ListView
        android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</FrameLayout>

list_view_item.xml(在布局文件夹中):

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:textSize="32sp"
    android:background="@drawable/normal_back" />

normal_back.xml(在drawable文件夹中):

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <solid android:color="#FFFFFF" />
</shape>

selected_back.xml(在drawable文件夹中):

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >
    <stroke
        android:width="2dp"
        android:color="#0000FF" />
    <solid android:color="#FFFFFF" />
</shape>

点击"Two"后的结果如下:

Android: AdapterView选择项目

英文:

You can check this sample project I just made. I think the code speaks for itself but feel free to ask questions if You aren't sure about something. But basically I set OnItemClickListener to the ListView and I change the background to selected_back which is a shape in drawable folder. Also, I keep a reference to the last changed View so when user click on another View it will be easy to change its background again to normal_back.

MainActivity.java

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import androidx.appcompat.app.AppCompatActivity;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity
{
View lastChangedView = null;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList&lt;String&gt; arrayList = new ArrayList&lt;&gt;();
arrayList.add(&quot;One&quot;);
arrayList.add(&quot;Two&quot;);
arrayList.add(&quot;Three&quot;);
final ArrayAdapter&lt;String&gt; adapter = new ArrayAdapter&lt;String&gt;(
this,
R.layout.list_view_item,
arrayList);
ListView listView = findViewById(R.id.listView);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
@Override
public void onItemClick(AdapterView&lt;?&gt; parent, View view, int position, long id)
{
if (lastChangedView != null)
{
lastChangedView.setBackgroundResource(R.drawable.normal_back);
}
lastChangedView = view;
Log.d(&quot;Main&quot;, &quot;Item click at &quot; + position);
view.setBackgroundResource(R.drawable.selected_back);
}
});
}
}

acitivty_main.xml

&lt;FrameLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
xmlns:tools=&quot;http://schemas.android.com/tools&quot;
android:layout_width=&quot;match_parent&quot;
android:layout_height=&quot;match_parent&quot;
tools:context=&quot;.MainActivity&quot;&gt;
&lt;ListView
android:id=&quot;@+id/listView&quot;
android:layout_width=&quot;match_parent&quot;
android:layout_height=&quot;match_parent&quot; /&gt;
&lt;/FrameLayout&gt;

list_view_item.xml (in layout folder)

&lt;TextView xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
android:layout_width=&quot;match_parent&quot;
android:layout_height=&quot;match_parent&quot;
android:textSize=&quot;32sp&quot;
android:background=&quot;@drawable/normal_back&quot; /&gt;

normal_back.xml (in a drawable folder)

&lt;shape xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
android:shape=&quot;rectangle&quot;&gt;
&lt;solid android:color=&quot;#FFFFFF&quot; /&gt;
&lt;/shape&gt;

selected_back.xml (in a drawable folder)

&lt;shape xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
android:shape=&quot;rectangle&quot; &gt;
&lt;stroke
android:width=&quot;2dp&quot;
android:color=&quot;#0000FF&quot; /&gt;
&lt;solid android:color=&quot;#FFFFFF&quot; /&gt;
&lt;/shape&gt;

Result (after clicking on "Two"):

Android: AdapterView选择项目

答案2

得分: 0

你需要一个自定义适配器来实现这个功能。它将简单地扩展BaseAdapter,并带有一个自定义视图以及一个布尔值,用于跟踪哪个项目被选中。你可以参考使用BaseAdapter与ListView的指南。

CustomAdatpter类将如下所示 -

public class MyAdapter extends BaseAdapter {

    private Context context;
    private ArrayList<String> arrayList;

    // 采用布尔值来跟踪选中的项目
    private boolean isItemSelected = false;

    public MyAdapter(Context context, ArrayList<String> arrayList) {
        this.context = context;
        this.arrayList = arrayList;
    }

    @Override
    public int getCount() {
        return arrayList.size();
    }

    @Override
    public Object getItem(int position) {
        return arrayList.get(position); // 返回指定位置的列表项
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {

        if (convertView == null) {
            convertView = LayoutInflater.from(context).
                    inflate(R.layout.item, parent, false);
        }

        TextView textView = (TextView) convertView.findViewById(R.id.text_view);
        textView.setText(arrayList.get(position));

        // 在convertView上设置点击监听器,这是每个项目视图
        convertView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isItemSelected) {
                    // 项目已选中,需要取消选中
                    isItemSelected = false;
                    textView.setBackgroundResource(R.drawable.unselected_bg);
                } else {
                    // 项目未选中,需要选中
                    isItemSelected = true;
                    textView.setBackgroundResource(R.drawable.selected_bg);
                }
            }
        });
        return convertView;
    }
}

我使用了R.drawable.unselected_bgR.drawable.selected_bg,它们实际上是如下所示的可绘制文件 -

selected_bg.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="#5B5BC9"/>
    <stroke android:color="#4CAF50" android:width="5dp"/>
</shape>

unselected_bg.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="#5B5BC9"/>
</shape>

最后,项目具有以下布局,在getView()中进行了膨胀:

item.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:clickable="true"
    android:focusable="true"
    android:id="@+id/text_view"
    android:background="@drawable/unselected_bg"
    android:padding="16dp">
</TextView>

如果你注意到,我在android:background="@drawable/unselected_bg"中设置了初始的未选中状态。

结果将如下所示 -

Android: AdapterView选择项目

祝愉快编码!

英文:

You need a custom adapter to achieve this. It will simply extend BaseAdater, and will have a custom view along with a boolean to keep info of which item was selected. You can follow Using a BaseAdapter with ListView guide.

CustomAdatpter class will be as follows -

public class MyAdapter extends BaseAdapter {
private Context context;
private ArrayList&lt;String&gt; arrayList;
//taking boolean to keep track of item selected
private boolean isItemSelected = false;
public MyAdapter(Context context, ArrayList&lt;String&gt; arrayList) {
this.context = context;
this.arrayList = arrayList;
}
@Override
public int getCount() {
return arrayList.size();
}
@Override
public Object getItem(int position) {
return arrayList.get(position); //returns list item at the specified position
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(context).
inflate(R.layout.item, parent, false);
}
TextView textView = (TextView) convertView.findViewById(R.id.text_view);
textView.setText(arrayList.get(position));
//setting click listener on convertView which is each item view
convertView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (isItemSelected){
//item is selected, need to un select item, 
isItemSelected = false;
textView.setBackgroundResource(R.drawable.unselected_bg);
}
else{
//item is not selected, need to select item
isItemSelected = true;
textView.setBackgroundResource(R.drawable.selected_bg);
}
}
});
return convertView;
}
}

I am using R.drawable.unselected_bg and R.drawable.selected_bg which are nothing but drawable files as follows -

selected_bg.xml

&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;shape xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;&gt;
&lt;solid android:color=&quot;#5B5BC9&quot;/&gt;
&lt;stroke android:color=&quot;#4CAF50&quot; android:width=&quot;5dp&quot;/&gt;
&lt;/shape&gt;

unselected_bg.xml

&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;shape xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;&gt;
&lt;solid android:color=&quot;#5B5BC9&quot;/&gt;
&lt;/shape&gt;

In last item has following layout which was inflated in getView();

item.xml

&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;TextView xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
android:layout_width=&quot;match_parent&quot;
android:layout_height=&quot;wrap_content&quot;
android:orientation=&quot;horizontal&quot;
android:clickable=&quot;true&quot;
android:focusable=&quot;true&quot;
android:id=&quot;@+id/text_view&quot;
android:background=&quot;@drawable/unselected_bg&quot;
android:padding=&quot;16dp&quot;&gt;
&lt;/TextView&gt;

If you notice, I have given android:background=&quot;@drawable/unselected_bg&quot; just to make item unselected on create.

Result will be as follows -

Android: AdapterView选择项目

Happy Coding !

huangapple
  • 本文由 发表于 2020年8月11日 22:34:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/63360417.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定