简体   繁体   English

如何自动更改android listview中的项目ID?

[英]how to change automatically the item id in android listview?

i have a custom adapter to place items inside listview.我有一个自定义适配器可以将项目放在列表视图中。 To customize it i have a listitem.xml file where i set the elements that compose a listitem.为了自定义它,我有一个 listitem.xml 文件,我在其中设置了组成列表项的元素。

They are as follows:它们如下:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="50dp" >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_marginLeft="5dp"
        android:scaleType="fitXY" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/textView1"
        android:layout_marginLeft="23dp"
        android:layout_marginTop="5dp"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="" />

    <ToggleButton
        android:id="@+id/toggleButton1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_alignParentRight="true"
        android:layout_marginRight="5dp"
        android:text=""/>

</RelativeLayout>

I have a classe Settings.java that uses the following layout settings.xml:我有一个使用以下布局 settings.xml 的类 Settings.java:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/relativeLayoutSettings"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#666666"
    android:orientation="vertical" >

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

</RelativeLayout>

Class Settings.java is like this:类 Settings.java 是这样的:

public class Settings extends Activity {

    private SensorAdapter sensorAdapter;
    private Context context;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
        setContentView(R.layout.settings);
        getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,
                R.layout.title_bar);

        context = getApplicationContext();

        sensorAdapter = new SensorAdapter();

        ListView sensorListview = (ListView) findViewById(R.id.listViewSettings);
        sensorListview.setAdapter(sensorAdapter);                   
        sensorListview.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                    long arg3) {

                sensorItem sensor = sensorAdapter.getCodeLearnChapter(arg2);

            }
        });
    }

    public class sensorItem {

        String sensorName;
        String sensorDescription;
        Drawable sensorImage;

    }

    public List<sensorItem> getDataForListView() {
        List<sensorItem> sensorsList = new ArrayList<sensorItem>();

        sensorItem sensorGps = new sensorItem();
        sensorGps.sensorName = "Location";
        sensorGps.sensorDescription = "Collect location";
        sensorGps.sensorImage = getResources().getDrawable(R.drawable.location);

        sensorItem sensorPhoto = new sensorItem();
        sensorPhoto.sensorName = "Photos";
        sensorPhoto.sensorDescription = "Collect photos";
        sensorPhoto.sensorImage = getResources().getDrawable(R.drawable.photos);

        sensorItem sensorAmplitude = new sensorItem();
        sensorAmplitude.sensorName = "Sound";
        sensorAmplitude.sensorDescription = "Collect amplitude";
        sensorAmplitude.sensorImage = getResources().getDrawable(
                R.drawable.amplitude);

        sensorItem sensorOrientation = new sensorItem();
        sensorOrientation.sensorName = "Orientation";
        sensorOrientation.sensorDescription = "Collect orientation";
        sensorOrientation.sensorImage = getResources().getDrawable(
                R.drawable.compass);

        sensorItem sensorSms = new sensorItem();
        sensorSms.sensorName = "Messages";
        sensorSms.sensorDescription = "Collect messages";
        sensorSms.sensorImage = getResources().getDrawable(R.drawable.sms);

        sensorItem sensorBattery = new sensorItem();
        sensorBattery.sensorName = "Battery";
        sensorBattery.sensorDescription = "Collect battery";
        sensorBattery.sensorImage = getResources().getDrawable(
                R.drawable.battery);

        sensorItem sensorCalendar = new sensorItem();
        sensorCalendar.sensorName = "Calendar";
        sensorCalendar.sensorDescription = "Collect calendar";
        sensorCalendar.sensorImage = getResources().getDrawable(
                R.drawable.calendar);

        sensorItem sensorAccelerometer = new sensorItem();
        sensorAccelerometer.sensorName = "Accelerometer";
        sensorAccelerometer.sensorDescription = "Collect accelerometer";
        sensorAccelerometer.sensorImage = getResources().getDrawable(
                R.drawable.accelerometer);

        sensorItem sensorLight = new sensorItem();
        sensorLight.sensorName = "Light";
        sensorLight.sensorDescription = "Collect luminosity";
        sensorLight.sensorImage = getResources().getDrawable(R.drawable.light);

        sensorItem sensorContacts = new sensorItem();
        sensorContacts.sensorName = "Contacts";
        sensorContacts.sensorDescription = "Collect contact";
        sensorContacts.sensorImage = getResources().getDrawable(
                R.drawable.contacts);

        sensorsList.add(sensorGps);
        sensorsList.add(sensorPhoto);
        sensorsList.add(sensorAmplitude);
        sensorsList.add(sensorOrientation);
        sensorsList.add(sensorSms);
        sensorsList.add(sensorBattery);
        sensorsList.add(sensorCalendar);
        sensorsList.add(sensorAccelerometer);
        sensorsList.add(sensorLight);
        sensorsList.add(sensorContacts);

        return sensorsList;
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    public class SensorAdapter extends BaseAdapter {

        List<sensorItem> sensorList = getDataForListView();

        private ToggleButton locationToggle, photosToggle, soundToggle,
        orientationToggle, messagesToggle, batteryToggle, calendarToggle,
        accelerometerToggle, lightToggle, contactsToggle;

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

        @Override
        public sensorItem getItem(int arg0) {
            return sensorList.get(arg0);
        }

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

        @Override
        public View getView(int arg0, View arg1, ViewGroup arg2) {

            if (arg1 == null) {
                LayoutInflater inflater = (LayoutInflater) Settings.this
                        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                arg1 = inflater.inflate(R.layout.listitem, arg2, false);
            }

            TextView sensorDescription = (TextView) arg1
                    .findViewById(R.id.textView2);
            ImageView sensorImage = (ImageView) arg1
                    .findViewById(R.id.imageView1);

            locationToggle = (ToggleButton) arg1.findViewById(R.id.toggleButton1);
            locationToggle.setChecked(true);

            locationToggle.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    Toast.makeText(context, "CARREGOU", Toast.LENGTH_LONG).show();

                }
            });

            sensorItem sensor = sensorList.get(arg0);        
            sensorDescription.setText(sensor.sensorDescription);
            sensorImage.setBackground(sensor.sensorImage);    
            return arg1;
        }

        public sensorItem getCodeLearnChapter(int position) {
            return sensorList.get(position);
        }

    }

}

The problem with this is that now every element in the listitem.xml has exactly the same ID.这样做的问题是现在 listitem.xml 中的每个元素都具有完全相同的 ID。 So every toggle button has the same ID.所以每个切换按钮都有相同的 ID。 I dont know which togglebutton the user pressed.我不知道用户按下了哪个切换按钮。

How can i know which togglebutton the user pressed?我怎么知道用户按下了哪个切换按钮? Do i have to change the way i populate the listview?我是否必须更改填充列表视图的方式?

Thx very much.非常感谢。

EDIT:编辑:

This is how it looks right now and the problem is that the ArrayList that i have to check whether a toggleButton in a row was clicked or not it seems to all set every element to true when i click in another row.这就是它现在的样子,问题是我必须检查一行中的 toggleButton 是否被单击的 ArrayList 当我单击另一行时,它似乎将每个元素都设置为 true。

Example: I have例子:我有

true |真实| true |真实| true真的

i click in the third button and i get我点击第三个按钮,我得到

true |真实| false |假| true真的

but if i click in the first button for example i get但如果我点击第一个按钮,例如我得到

false |假| true |真实| true真的

when i should get instead什么时候我应该得到

false |假| false |假| true.真的。

Here is the code adapter so someone can take a look.这是代码适配器,所以有人可以看看。

public class SensorAdapter extends BaseAdapter {

        List<sensorItem> sensorList = getDataForListView();
        private ToggleButton settingsToggle;
        private ArrayList<Boolean> checkedSensors;
        @Override
        public int getCount() {
            return sensorList.size();
        }

        @Override
        public sensorItem getItem(int arg0) {
            return sensorList.get(arg0);
        }

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

        @Override
        public View getView(int arg0, View arg1, ViewGroup arg2) {

            if (arg1 == null) {
                LayoutInflater inflater = (LayoutInflater) Settings.this
                        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                arg1 = inflater.inflate(R.layout.listitem, arg2, false);
            }

            // TextView sensorName = (TextView)
            // arg1.findViewById(R.id.textView1);
            TextView sensorDescription = (TextView) arg1
                    .findViewById(R.id.textView2);
            ImageView sensorImage = (ImageView) arg1
                    .findViewById(R.id.imageView1);

            settingsToggle = (ToggleButton) arg1.findViewById(R.id.toggleButton1);          
            settingsToggle.setChecked(true);
            checkedSensors = new ArrayList<Boolean>();
            int i = 0;
            while(i < 10){
                checkedSensors.add(i,true);
                i++;
            }
            settingsToggle.setTag(new Long(getItemId(arg0)));
            settingsToggle.setOnClickListener(mOnToggleListener);

            /*settingsToggle.setOnCheckedChangeListener(new OnCheckedChangeListener(){

                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked){
                    if(isChecked){
                        Toast.makeText(Settings.this, "on "+buttonView.getId(), Toast.LENGTH_LONG).show();

                    }
                    else{
                        Toast.makeText(Settings.this, "off "+buttonView.getId(), Toast.LENGTH_LONG).show();
                    }

                }

            });*/

            sensorItem sensor = sensorList.get(arg0);

            // sensorName.setText(sensor.sensorName);
            sensorDescription.setText(sensor.sensorDescription);
            sensorImage.setBackground(sensor.sensorImage);

            return arg1;
        }

        public OnClickListener mOnToggleListener = new OnClickListener(){

            @Override
            public void onClick(View v){
                long id = (Long) v.getTag();

                if (checkedSensors.get((int)id)){
                    //enableSensor(id);
                    checkedSensors.add((int)id, false);
                }else{
                    //disableSensor(id);
                    checkedSensors.add((int)id, true);
                }
                for(int i = 0; i<10 ; i++){
                    System.out.println(i + " " + checkedSensors.get(i));
                }

            }
        };

        public sensorItem getSensor(int position) {
            return sensorList.get(position);
        }
    }
}

You can set the index in a tag on the toggle button so the onClick event knows which index got clicked.您可以在切换按钮上的标签中设置索引,以便 onClick 事件知道点击了哪个索引。

Before you set the onClick listener add this line:在设置 onClick 侦听器之前添加以下行:

locationToggle.setTag(arg0);

And inside your onClick listener:在您的 onClick 侦听器中:

int position = (Integer)v.getTag();

you can create your listener ouside of getView like this:你可以像这样在 getView 之外创建你的监听器:

public OnClickListener mOnToggleListener = new OnClickListener() {

        @Override
        public void onClick(View v) {

            //get id of your item from view
            //v is locationToggleView
            long id = (Long)v.getTag();

        }
};

and make these change in getView method:并在 getView 方法中进行这些更改:

//set id as view tag when create or reuse view
//arg0 is position
locationToggle.setTag(new Long(getItemId(arg0)));
locationToggle.setOnClickListener(mOnToggleListener);

by this way you can get view related item id when locationToggle is clicked.通过这种方式,您可以在单击 locationToggle 时获取查看相关项目 ID。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM