繁体   English   中英

如何在不切换活动的情况下使用来自另一个活动的数据和按钮单击从主活动编辑数组?

[英]How can I edit an Array from Main Activity with the data and button click from another Activity without switching between Activities?

我试图在主活动中初始化一个自定义数组。 我想从另一个包含数据和按钮单击的活动更新/编辑数组中的元素。 我的主要活动是Main Activity ,我的第二个活动是Display 有人可以帮忙吗?

public class MainActivity extends AppCompatActivity {

    public Pets[] arrayList=new Pets[]{
            new Pets(R.drawable.dog,"Dog","Wolf","The dog is a domesticated descendant of the wolf. Also called the domestic dog"),
            new Pets(R.drawable.bird,"Bird","Unknown!","Birds are a group of warm-blooded vertebrates constituting the class Aves characterised by feathers, toothless beaked jaws"),
            new Pets(R.drawable.cat,"Cat","Tiger","The cat is a domestic species of small carnivorous mammal"),
    };

        textd = ed.getText().toString();
       
        ed.setVisibility(View.GONE);
        d.setVisibility(View.VISIBLE);

        d.setText(textd);

        Intent i = new Intent(Display.this, MainActivity.class);

        i.putExtra("edit", textd);
     
        i.putExtra("pos", pos);
        i.putExtra("click", click);

        startActivity(i);


        finish();

此代码在显示活动中。 我需要更改此活动的数据而不是切换到MainActivity

Display Activity中获取数组中要更改的数据后。 可以使用共享首选项

SharedPreferences share=getSharedPreferences("myArray",MODE_PRIVATE);
            SharedPreferences.Editor editor=share.edit();
            editor.putString("desc",textd);
            editor.putInt("pos",pos);
            editor.putInt("click",click);
            editor.apply();

在存在数组的活动中进行更改

 SharedPreferences share=getSharedPreferences("myArray",MODE_PRIVATE);
            pos=share.getInt("pos",0);
            text=share.getString("desc","");
            arrayList[pos]=text;

首先不要在 MainActivity 中创建数据。 活动是您的视图,如果您将数据源与视图分开,您可以很容易地更新它。

暂无
暂无

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

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