Add a
EditText
element your your "main.xml" layout file.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<EditText
android:id="@+id/myView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10" >
<requestFocus />
</EditText>
</LinearLayout>
Create a new menu XML resource with the file name "contextual.xml"
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="@+id/toast"
android:title="Toast">
</item>
</menu>
Change your
Activity
to the following.
package de.vogella.android.socialapp;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;
public class OverviewActivity extends Activity {
protected Object mActionMode;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
View view = findViewById(R.id.myView);
view.setOnLongClickListener(new View.OnLongClickListener() {
public boolean onLongClick(View view) {
if (mActionMode != null) {
return false;
}
mActionMode = OverviewActivity.this
.startActionMode(mActionModeCallback);
view.setSelected(true);
return true;
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.mainmenu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Toast.makeText(this, "Just a test", Toast.LENGTH_SHORT).show();
return true;
}
private ActionMode.Callback mActionModeCallback = new ActionMode.Callback() {
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.contextual, menu);
return true;
}
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.toast:
Toast.makeText(OverviewActivity.this, "Selected menu",
Toast.LENGTH_LONG).show();
mode.finish();
return true;
default:
return false;
}
}
public void onDestroyActionMode(ActionMode mode) {
mActionMode = null;
}
};
}
If you run this example and long press the
EditText
widget, your contextual
ActionBar
is displayed.
hey thanks , but public
ReplyDeleteboolean onCreateOptionsMenu(Menu menu) , is not in use !
This comment has been removed by the author.
ReplyDelete