android - 如何动态编辑和保存列表项文本?

标签 android database sharedpreferences

你好这段代码中的 friend 我正在尝试编辑列表项的文本并保存列表项中的最新文本,即使在此处关闭应用程序后我们也可以成功地检索带有编辑文本选项的对话框中的文本已经在 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)

最佳答案

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

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() 中填充你的数组/数组列表> 方法。

关于android - 如何动态编辑和保存列表项文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36251400/

相关文章:

android - 无法解析方法 getProjection() 和 getMapCenter()

php - 某些数据库条目被忽略

java - 记录数据库更新中更改的字段/列

c++ - MATLAB 中的 mysql.cpp 编译错误

java - SharedPreference 不包含广播接收器内的任何内容

java - 无法在 ConstraintLayout 中定位 TextView

android - 杀死 Activity 的所有实例

android - 多个模块项目中的每个 AndroidManifest 可以有自己的 <application> 部分吗?模块之间如何共享资源?

java - 奇怪的异常 : Cannot cast String to Boolean when using getBoolean

android - 解释在不同 Android 设备上访问 SharedPreferences 的性能差异