操作栏后退按钮无法正常工作

时间:2016-03-28 15:59:50

标签: android android-actionbar

我正在尝试制作笔记应用。基本上,当我点击列表视图中的某个项目时,当项目的名称可编辑时,这将带我到另一个活动。当我编辑文本并单击操作栏中的后退按钮时,应在主活动中更新文本,但这不会发生;但是当我使用android后退按钮(设备之一)时它工作正常。

这是我的代码

public class MainActivity extends AppCompatActivity {

ListView MemoContent ;
static ArrayList<String> MyArray ;
static ArrayAdapter MyAdapter ;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    MemoContent = (ListView) findViewById(R.id.MemoContent) ;
    MyArray = new ArrayList<>() ;
    MyArray.add("Example Note") ;

     MyAdapter = new ArrayAdapter(this , android.R.layout.simple_list_item_1 , MyArray);
    MemoContent.setAdapter(MyAdapter);

    MemoContent.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Intent i = new Intent(getApplicationContext() , EditMemo.class) ;
            i.putExtra("note" , position) ;
            startActivity(i);


        }
    });

}

这是第二个活动

public class EditMemo extends AppCompatActivity implements TextWatcher {

EditText editText ;
int id;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_edit_memo);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    editText = (EditText) findViewById(R.id.editText) ;

    Intent  j = getIntent() ;
    id = j.getIntExtra("note" , -1) ;
    if(id!=-1)
    {
        editText.setText(MainActivity.MyArray.get(id));
    }

    editText.addTextChangedListener(this);
}


@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {

}

@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {

    MainActivity.MyArray.set(id , String.valueOf(s)) ;
    MainActivity.MyAdapter.notifyDataSetChanged();

}

@Override
public void afterTextChanged(Editable s) {

}

}

提前致谢..

1 个答案:

答案 0 :(得分:1)

请务必将元数据标记和 android:parentActivityName 属性添加到清单中的子活动声明中,如下所示:

 <activity
      android:name=".EditMemo"
      android:parentActivityName=".MainActivity">
          <meta-data
              android:name="android.support.PARENT_ACTIVITY"
              android:value="full.package.name.to.MainActivity" />
   </activity>

如果您的目标是API级别16及以上 ,则需要 android:parentActivityName 属性