如何动态编辑和保存listitem文本?

时间:2016-03-27 19:06:02

标签: android database sharedpreferences

你好朋友在这段代码中我正在尝试编辑listitem的文本并保存列表项中的最新文本,即使应用程序关闭后我们也可以在对话框中使用编辑文本选项成功检索文本,这是已经在listitem中只需要将预定义更改为任何文本 帮助这个小东西 提前致谢

MainActivity.java:

package com.example.vks_module;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.jar.Attributes.Name;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

    private ListView mainListView;
    private ArrayAdapter<String> listAdapter;
    final Context context = this;

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

        mainListView = (ListView) findViewById(R.id.lv1);
        String[] planets = new String[] { "Mercury", "Venus", "Earth", "Mars",
                "Jupiter", "Saturn", "Uranus", "Neptune" };
        final ArrayList<String> planetList = new ArrayList<String>();
        planetList.addAll(Arrays.asList(planets));

        listAdapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, planetList);

        mainListView.setAdapter(listAdapter);

        mainListView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int pos,
                    long id) {
                String message = planetList.get(pos);
                final int positions = mainListView.getSelectedItemPosition();
                final Dialog dialog = new Dialog(context);
                dialog.setContentView(R.layout.customdialog);
                dialog.setTitle("Change the name");

                final TextView plan_names = (TextView) dialog
                        .findViewById(R.id.name);
                Button set = (Button) dialog.findViewById(R.id.Set);
                plan_names.setText(message);
                set.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {

                        String name = plan_names.getText().toString();

                        int pos = positions;
                        if (!name.isEmpty() && name.length() > 0) {
                            // remove
                            listAdapter.remove(planetList.get(pos));
                            // insert the updated one
                            listAdapter.insert(name, mainListView.getSelectedItemPosition());

                            listAdapter.notifyDataSetChanged();

                        } else {
                            Toast.makeText(getApplicationContext(),
                                    "Are you serious", Toast.LENGTH_SHORT)
                                    .show();
                        }

                    }

                });

                dialog.show();

            }

        });

    }

    @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 boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

**activitymain.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="com.example.vks_module.MainActivity" >
<ListView 
    android:id="@+id/lv1"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_centerHorizontal="true"
    android:padding="10dp"
    />
</RelativeLayout>


**customedailog.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"
    android:background="@android:color/holo_blue_light"
    android:orientation="vertical" >

    <EditText
        android:id="@+id/name"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:layout_centerHorizontal="true"
        android:gravity="center_horizontal"
        android:layout_marginTop="100dp"
        android:background="@android:color/transparent" />

    <Button
        android:id="@+id/Set"
        android:layout_below="@+id/name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="20dp"
        android:text="SET" />

</RelativeLayout>


**LOGCAT**

03-28 00:17:38.767: D/AndroidRuntime(26713): Shutting down VM
03-28 00:17:38.774: E/AndroidRuntime(26713): FATAL EXCEPTION: main
03-28 00:17:38.774: E/AndroidRuntime(26713): Process: com.example.vks_module, PID: 26713
03-28 00:17:38.774: E/AndroidRuntime(26713): java.lang.ArrayIndexOutOfBoundsException: length=10; index=-1
03-28 00:17:38.774: E/AndroidRuntime(26713):    at java.util.ArrayList.get(ArrayList.java:310)
03-28 00:17:38.774: E/AndroidRuntime(26713):    at com.example.vks_module.MainActivity$1$1.onClick(MainActivity.java:71)
03-28 00:17:38.774: E/AndroidRuntime(26713):    at android.view.View.performClick(View.java:5204)
03-28 00:17:38.774: E/AndroidRuntime(26713):    at android.view.View$PerformClick.run(View.java:21153)
03-28 00:17:38.774: E/AndroidRuntime(26713):    at android.os.Handler.handleCallback(Handler.java:739)
03-28 00:17:38.774: E/AndroidRuntime(26713):    at android.os.Handler.dispatchMessage(Handler.java:95)
03-28 00:17:38.774: E/AndroidRuntime(26713):    at android.os.Looper.loop(Looper.java:148)
03-28 00:17:38.774: E/AndroidRuntime(26713):    at android.app.ActivityThread.main(ActivityThread.java:5417)
03-28 00:17:38.774: E/AndroidRuntime(26713):    at java.lang.reflect.Method.invoke(Native Method)
03-28 00:17:38.774: E/AndroidRuntime(26713):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
03-28 00:17:38.774: E/AndroidRuntime(26713):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

2 个答案:

答案 0 :(得分:2)

如果您看到方法getSelectedItemPosition()的文档,则如果未选择任何内容,则返回INALID_ROW_ID(其值为-1)。我认为当您在ListView中选择一个项目时,您正在启动一个Dialog获得焦点,ListView中的项目将被取消选中,这就是为什么mainListView.getSelectedItemPosition()代码总是返回-1。而是使用方法pos中的参数onItemClick(),如下所示。

mainListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int pos,
                                    long id) {
                String message = planetList.get(pos);
                final int positions = pos; //change here
                final Dialog dialog = new Dialog(context);
                dialog.setContentView(R.layout.customdialog);
                dialog.setTitle("Change the name");

                final TextView plan_names = (TextView) dialog
                        .findViewById(R.id.name);
                Button set = (Button) dialog.findViewById(R.id.Set);
                plan_names.setText(message);
                set.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {

                        String name = plan_names.getText().toString();
                        if (!name.isEmpty() && name.length() > 0) {
                            // remove
                            listAdapter.remove(planetList.get(positions)); //change here
                            // insert the updated one
                            listAdapter.insert(name, positions); //change here

                            listAdapter.notifyDataSetChanged();

                        } else {
                            Toast.makeText(getApplicationContext(),
                                    "Are you serious", Toast.LENGTH_SHORT)
                                    .show();
                        }
                        dialog.dismiss(); //add this to dismiss dialogue after entering the string

                    }

                });

                dialog.show();

            }

        });

如果要在重新启动应用程序后保存更改并获取新值,则应将新值保存在数据库中,并使用它们在onCreate()方法中填充数组/ arraylist。

答案 1 :(得分:0)

问题出在

final int positions = mainListView.getSelectedItemPosition();

所以, 当您单击ListView项目时,它不会将其状态更改为“已选择”,因此,当事件发生时您执行以下操作:

mainListView.getSelectedItem()

该方法无法返回任何内容。你要做的就是使用这个位置并获得底层物体。

你已经在变量pos中拥有相同的内容,但是你在

覆盖了它
int pos = positions;

检查一下,你很高兴!