我正在写一个备忘录应用程序,但有一些问题当我想编辑备忘录,无论我选择的项目,它总是只改变第一个项目,它只得到了字符串Like this前面的项目编号我想的结果是,我可以改变我点击的任何项目
这是我的代码:
public class d_Game_message extends AppCompatActivity
implements AdapterView.OnItemClickListener, AdapterView.OnItemLongClickListener {
private static final int REQUEST_CODE_EDIT = 1;
String[] aMemo ={
"1.按一下可以編輯備忘",
"2.長按可以清除備忘","3.","4.","5.","6."};
ListView lv;
ArrayAdapter<String> aa;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dgame_message);
lv = (ListView)findViewById(R.id.listView);
aa = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1, aMemo);
lv.setAdapter(aa);
lv.setOnItemClickListener(this);
lv.setOnItemLongClickListener(this);
@Override
public void onItemClick(AdapterView<?> a, View v, int pos, long id) {
Intent it = new Intent(this, d_Game_message_edit.class);
it.putExtra("requestCode",pos); //附加編號
it.putExtra("memo", aMemo[pos]); //附加備忘項目的內容
activityResultLaunch.launch(it);
}
@Override
public boolean onItemLongClick(AdapterView<?> a, View v, int pos, long id) {
aMemo[pos] = (pos+1) + "."; //將內容清除 (只剩編號)
aa.notifyDataSetChanged(); //通知 Adapter 要更新陣列內容
return true; //傳回 true 表示此事件已處理
}
ActivityResultLauncher<Intent> activityResultLaunch = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
Intent data = result.getData();
int requestCode = data.getIntExtra("requestCode", 0);
aMemo[requestCode] = data.getStringExtra("memo");
aa.notifyDataSetChanged();
}
}
});
这是编辑活动
public class d_Game_message_edit extends AppCompatActivity {
TextView txv;
EditText edt;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dgame_message_edit);
Intent it = getIntent();
String s = it.getStringExtra("memo");
txv = (TextView)findViewById(R.id.textView);
txv.setText(s.substring(0, 2));
edt = (EditText)findViewById(R.id.editText);
if(s.length() > 3)
edt.setText(s.substring(2));
}
public void onCancel(View v) {
setResult(RESULT_CANCELED);
finish();
}
public void onSave(View v) {
Intent it2 = new Intent();
it2.putExtra("memo", txv.getText() + " " + edt.getText());
setResult(RESULT_OK, it2);
finish();
}
}
我是一个新手,非常感谢你的帮助!!
1条答案
按热度按时间dfuffjeb1#
在
onSave
的Activity
中,您正在设置"memo"
文本,但您没有返回"requestCode"
,因此int requestCode = data.getIntExtra("requestCode", 0);
始终为0
(因为缺少"requestCode"
键时,0
被设置为默认参数),因此编辑项将始终为位置= 0处的此项。将通过的
"requestCode"
存储在d_Game_message_edit
Activity
中(在onCreate
中读取)并在运行
onSave
时在"memo"
文本旁边的相同Intent
中返回它并更改
"requestCode"
命名,它可能会令人困惑...