I am working on a Project and testing the XML, however, whenever I try switching to my next activity, the app gets stuck on a black screen and does nothing, and I am forced to quit.
I tried switching the layouts for setContentView and that didn't work, I checked to make sure the code in the activity files was working, and now I am looking at other's questions and I am just confused.
Here is my MainActivity:
public class MainActivity extends android.app.Activity {
ImageButton startButton;
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_main);
startButton = (ImageButton)findViewById(R.id.startButton);
textView = (TextView)findViewById(R.id.textView);
textView.setTextColor(Color.WHITE);
View backgroundView = findViewById(R.id.spoopySkellington);
View root = backgroundView.getRootView();
root.setBackgroundColor(getResources().getColor(android.R.color.black));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
public void startClick(View view)
{
final Intent intent = new Intent(MainActivity.this, AdventureActivity.class);
startActivity(intent);
}
#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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Here is the activity I am trying to switch to.
public class AdventureActivity extends android.app.Activity {
Character mainCharacter;
Character skeleton;
TextView dialogueView;
EditText textField;
Button confirmButton;
String field;
ImageView enemy;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_adventure);
confirmButton = (Button)findViewById(R.id.confirmButton);
dialogueView = (TextView)findViewById(R.id.dialogueView);
textField = (EditText)findViewById(R.id.inputText);
field = "";
skeleton = new Character("Skeleton", 10, 1);
String name = "";
while (field.equals("")) {
dialogueView.setText("What is your name?");
name = field;
}
mainCharacter = new Character(name);
}
public void onClick(View view)
{
field = textField.getText().toString();
textField.setText("");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Lastly, here is the activity xml for the one I want to switch to:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.example.jason.textadventure.AdventureActivity"
tools:showIn="#layout/activity_adventure">
<TextView
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:id="#+id/dialogueView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="..."
android:textSize="30dp"
tools:layout_editor_absoluteY="126dp"
tools:layout_editor_absoluteX="180dp"
/>
<EditText
app:layout_constraintBottom_toBottomOf="#id/dialogueView"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:id="#+id/inputText"
android:layout_width="261dp"
android:layout_height="40dp"
tools:layout_editor_absoluteY="196dp"
tools:layout_editor_absoluteX="62dp"
android:inputType="textNoSuggestions"
/>
<Button
app:layout_constraintBottom_toBottomOf="#id/inputText"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="#id/dialogueView"
android:id="#+id/confirmButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="CONFIRM"
android:onClick="onClick"
tools:layout_editor_absoluteY="184dp"
tools:layout_editor_absoluteX="148dp" />
When onCreate() is called, your code is stuck around this loop
while (field.equals("")) {
dialogueView.setText("What is your name?");
name = field;
}
Related
I have a main_activity with 3 different Fragment and a SlideActivity. I could make transactions among 3 fragments successfully in my MainActivity.
Now I add 1 button in the MainActivity and it will open the SlideActivity. On the SlideActivity, there are 3 buttons in the navigation bar to switch to each different fragments which I already created.
The problem is when I click the list button in the navigation, an error comes out shows that
No view found for id 0x7f080052 (com.example.learnfragment:id/fragment_container) for fragment fragment_main{e1acaf7 #0 id=0x7f080052}
It seems that it cannot find the FrameLayout ID by R.id. and I believe because the navigation buttons are in the SlideActivity and it cannot find the ID which is in the MainActivity.
But how should I do for switching back to the MainActivity as well as changing different fragment?
Here's the navigation_slide_activity.xml
<include
layout="#layout/app_bar_slide"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_slide"
app:menu="#menu/activity_slide_drawer" />
The Navigation_Slide_Activity.java:
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_home) {
// Navigate back to the Main Fragment
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.fragment_container, new fragment_main());
ft.commit();
}
}
And the main_activity.xml:
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="392dp"
android:layout_height="496dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp" />
Finally, the MainActivity.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create Fragment
if(savedInstanceState == null){
getSupportFragmentManager().beginTransaction().add(
R.id.fragment_container,
new fragment_main()).commit();
}
}
Get a public static variable in your MainActivity.
public static int FRAGMENT_TO_BE_LOADED = 0;
Now from the SlideActivity, set the variable to a number (e.g. 3, that is you want to move to the third fragment when you are returning to your MainActivity.
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_home) {
MainActivity.FRAGMENT_TO_BE_LOADED = 3;
finish();
}
}
Now in your MainActivity, you need to have an onResume function which will check the variable and load the fragment accordingly.
#Override
protected void onResume() {
super.onResume();
if(FRAGMENT_TO_BE_LOADED == 1) loadFragment1();
else if(FRAGMENT_TO_BE_LOADED == 2) loadFragment2();
else if(FRAGMENT_TO_BE_LOADED == 3) loadFragment3();
}
Hope that solves your problem.
I am having trouble with using OnClickListener. I am trying to start a new activity when the user presses one of the buttons in my floating action button. My app just crashes right when I run it.
In my LaunchActivity.java:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_launch);
final Button buttonNote = (Button) findViewById(R.id.note);
buttonNote.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
startActivity(new Intent(LaunchActivity.this, CreateNote.class));
}
});
}
In my activity_launch.xml:
<com.getbase.floatingactionbutton.FloatingActionsMenu
android:id="#+id/create"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
fab:fab_addButtonColorNormal="#color/accent"
fab:fab_addButtonColorPressed="#color/accent_dark"
fab:fab_addButtonPlusIconColor="#color/window_background"
fab:fab_labelStyle="#style/menu_labels_style"
android:layout_marginBottom="16dp"
android:layout_marginEnd="16dp">
<com.getbase.floatingactionbutton.FloatingActionButton
android:id="#+id/note"
android:src="#drawable/ic_note"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:paddingBottom="16dp"
fab:fab_title="#string/note"
fab:fab_colorNormal="#color/accent"
fab:fab_colorPressed="#color/accent_dark"/>
</com.getbase.floatingactionbutton.FloatingActionsMenu>
CreateNote.java:
public class CreateNote extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_note);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_create_note, 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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Thank you for any help, this is my first app.
try this
findViewById(R.id.note).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LaunchActivity.this, CreateNote.class));
}
});
instead
final Button buttonNote = (Button) findViewById(R.id.note);
buttonNote.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
startActivity(new Intent(LaunchActivity.this, CreateNote.class));
}
});
hope it help
Please share your logcat errors here..
And try to change the object from Button to com.getbase.floatingactionbutton.FloatingActionButton.
Declare your activity in manifest file as follows
<activity
android:name=".CreateNote"
android:label="#string/app_name">
</activity>
Ok, you got it working, but for your information,
the reason why you were facing this problem was, the FAB is NOT one of those simple buttons that you create.
You have to create an object of floatingActionButton instead of creating the object of button (which you did in your case).
I am making an Facts based application. I want it to show new fact every time the user presses the button and i also want that when the user exits the app and restart it, it would resume from the same fact that user was reading.
Help me guys... I have included the java and xml code that i am using
Thanks in advance
My Java Layout
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void Next(View view) {
TextView textView = (TextView) findViewById(R.id.textView);
textView.setText("Hi");
textView.setText("No One is here to sleep");
textView.setText("This sounds like fun");
textView.setText("Men will be men");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is
// present.
getMenuInflater().inflate(R.menu.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();
// noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity"
android:background="#ff7922ff">
<TextView android:text="#string/hello_world"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView"
android:textSize="35dp"
android:layout_above="#+id/button"
android:layout_centerHorizontal="true"
android:layout_marginBottom="106dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Next"
android:id="#+id/button"
android:layout_marginBottom="158dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:onClick="Next" />
</RelativeLayout>
TextView tv = (TextView)findViewById(R.id.tv);
Button bt = (Button)findViewById(R.id.bt);
bt.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
tv.setText("TEXT");
}
});
Use SharedPreferences for that
SharedPreferences prefs = getSharedPreferences("mySHaredpref", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
boolean isFirst = prefs.getInt("lastFact", 0);
You could use Shared Preferences to keep a track of which was the last fact that the user had seen. Please check this link for the same How to use SharedPreferences in Android to store, fetch and edit values
What you will need to do is that on every next or previous button click you will have to store the fact number in your shared preferences. Every time the app is opened, load fact corresponding to the factnumber in the sharedpreferences.
I would advice you to do like this:
int count=0;
ArrayList<String> msgList = new ArrayList<>();
msgList.add("Hi");
msgList.add("No One is here to sleep");
msgList.add("This sounds like fun");
msgList.add("Men will be men");
Now
public void Next(View view) {
if(count==msgList.size()){
count=0;
textView.setText(msgList.get(count%msgList.size()));
}else{
textView.setText(msgList.get(count%msgList.size()));
count++;
}
}
As per your requirement, you need to save the facts in shared preferences and show the facts in TextView as user tap the button.
You also need to fetch the facts from shared preferences and show on the TextView in OnResume() of activity.
Button btn = (Button)findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// save the facts in shared preferences
// and show the facts on the text view
}
});
and onResume()
#Override
protected void onResume() {
super.onResume();
// check the shared preferences for the facts
// If facts is available in shared preferences then show on the
// textview
}
If you want to define the onClick method on XML, then work on onClickListener to be done on the onClick method(defined in XML).
I made an android app in which the user click the favorite menu item button and the page name saves in the favorite.class activity. But when I click on any item in the favorite list it opens only one specific class and not others which I want. Here is my code please look at the code and tell me what should I do to make it first in ListView form and then to click the item which opens the correct activity from it.
favorite.xml layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:layout_marginLeft="17dp">
<TextView
android:id="#+id/empty_textview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/no_bookmark"
android:textSize="16sp"
android:textColor="#000000"
android:
android:textStyle="bold"/>
<TextView
android:id="#+id/bookmark_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="10dp"
android:textSize="16sp"
android:textColor="#000000"
android:textStyle="bold"/>
<!-- ScrollView is needed when adding views, or only the last view will show up -->
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:id="#+id/bookmark_insert_point"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
</LinearLayout>
</ScrollView>
</LinearLayout>
Favorite.Class activity:
public class Favorite extends Activity {
private TextView mEmptyText;
private LinearLayout mBookmarkLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.favorite);
// this code is used for the action bar color change//
ActionBar bar = getActionBar();
bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#6B8E23")));
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
mEmptyText = (TextView) findViewById(R.id.empty_textview);
mBookmarkLayout = (LinearLayout) findViewById(R.id.bookmark_insert_point);
getAllKeys();
}
private void getAllKeys()
{
SharedPreferences sp = this.getSharedPreferences("bookmarks", MODE_PRIVATE);
Map<String,?> keys = sp.getAll();
int count = 0;
for(Map.Entry<String,?> entry : keys.entrySet())
{
String value = entry.getValue().toString();
System.out.println("!!!!!!!!!!!!!!!!!value = "+value);
String delimiter = ",";
String[] values_array = value.split(delimiter);
addBookmark(values_array);
count++; //keep track of the number of bookmarks
}
//if there are no bookmarks, display a text view saying so. Otherwise, make the text view go away
if (count == 0)
{
mEmptyText.setVisibility(View.VISIBLE);
mEmptyText.setText(getString(R.string.no_bookmark));
}
else
mEmptyText.setVisibility(View.GONE);
}
#SuppressWarnings("deprecation")
private void addBookmark(final String[] values_array)
{
LayoutInflater vi = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = vi.inflate(R.layout.favorite, null);
final TextView text = (TextView) v.findViewById(R.id.bookmark_text);
text.setText(values_array[1]);
// insert into main view
mBookmarkLayout.addView(v, 0, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT));
System.out.println("!!!!!!!!!!!!!!!!!!!!Just added a view");
text.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(text.equals("Atherosclerosis"));
Intent i=new Intent(Favorite.this,Atherosclerosis.class);
startActivity(i);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.favorite, menu);
return true;
}
}
and finally the activity from where user click for add to favorite:
public boolean onOptionsItemSelected(MenuItem item) {
// Take appropriate action for each action item click
switch (item.getItemId()) {
case R.id.id_search:
Intent newActivity0 = new Intent(this,Search.class);
startActivity(newActivity0);
return true;
case R.id.id_favorit:
SharedPreferences sp = this.getSharedPreferences("bookmarks", MODE_PRIVATE);
Editor editor = sp.edit();
editor.putString("atherosclerosis", "com.kmcpesh.shortreviewofcardiology.Favorite,Atherosclerosis");
editor.commit();
Toast.makeText(getApplicationContext(), "Item Added to Favorite List!", Toast.LENGTH_SHORT).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
well i guess what you have to do is setOnItemClickListener in everyone of the list items...
an example is
private void registerCallClickBack() {
// TODO Auto-generated method stub
ListView list = (ListView)findViewById(R.id.listView1);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View viewClicked, int position,
long id) {
// TODO Auto-generated method stub
//String message = "You have chosen the " + id + "item";
//Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();
Intent intent = new Intent("package.Activity name");
startActivity(intent);
}
});
}
this will either display a toast message of every listview item clicked or start a new intent..
I'm trying to make the actionbar menu (onCreateOptionsMenu) open ONLY on a long-click. How would I achieve this? At the moment I have it working for just a single short press/click using the following code:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
// TODO: Only onlongclick should the menu be revealed
getMenuInflater().inflate(R.menu.my_menu_id, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_home:
open_home();
return true;
case R.id.menu_how_to:
open_how_to();
return true;
case R.id.menu_rate:
open_rate();
return true;
case R.id.menu_about:
open_about();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
I'd like the menu to ONLY open for a long click (sort of like a hidden/trick feature). I've looked into onLongClickListener but can't get it to work. After the menu is opened it can behave normally (no more longclicks needed). Thanks for your help! Really appreciate it.
This is not possible. LongClick on the ActionBar buttons is not overridable.
It will always show a toast with the name of the button you long pressed. This is a help and discovery feature.
Okay so there's 2 answers to this depending on whether you would like icons in the menu:
Create a context menu, however each row of the menu cannot have icons next to it. This is the simpler method.
Create an alert dialog with a menu. This is much more complex but you can add icons and make the menu much more customisable.
I personally prefer method 2 because of the icons. I'll run through these methods below. First I'll just setup the action bar and button for the menu.
Sp first create an image button to open the menu somewhere. Also open up the custom action bar. This code is for BOTH methods:
// This goes somewhere in the activity's onCreate
ImageButton menu_home_button = (ImageButton) findViewById(R.id.action_bar_menu_home);
registerForContextMenu(menu_home_button); //ONLY USE THIS FOR METHOD1
menu_home_button.setLongClickable(true);
menu_home_button.setClickable(true);
// Custom action bar
actionBar = getActionBar();
actionBar.setCustomView(R.layout.my_custom_actionbar);
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayShowCustomEnabled(true);
actionBar.setDisplayUseLogoEnabled(false);
actionBar.setDisplayShowHomeEnabled(false);
My ImageButton was overlayed on top of the action bar on the right and looked like this in my_custom_actionbar.xml:
<ImageButton
android:background="?android:selectableItemBackground"
android:id="#+id/action_bar_menu_home"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/menu_icon"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginRight="4dp"
android:clickable="true"
android:focusable="true"
android:longClickable="true" />
--------------------------------------
METHOD 1:
Add this to onCreate in WebViewActivity.java:
// Do the long press stuff
menu_home_button.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
Toast.makeText(getApplicationContext(), "Long Press works...", Toast.LENGTH_SHORT).show();
// Do whatever you want on the longclick
}
});
The following code goes where onCreateOptionsMenu and onOptionsItemSelected would go (at the end of the java class -- mine was called WebViewActivity.java).
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.my_menu_id, menu);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
switch (item.getItemId()) {
case R.id.menu_home:
open_home();
return true;
case R.id.menu_how_to:
open_how_to();
return true;
case R.id.menu_rate:
open_rate();
return true;
case R.id.menu_about:
open_about();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
Then you create your menu in my_menu_id.xml. Including icons in the XML won't work so don't bother trying:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.example.yourapp.WebViewActivity" >
<item
android:id="#+id/menu_home"
android:title="#string/menu_home"
android:showAsAction="never"/>
<item
android:id="#+id/menu_how_to"
android:title="#string/menu_how_to"
android:showAsAction="never"/>
<item
android:id="#+id/menu_rate"
android:title="#string/menu_rate"
android:showAsAction="never"/>
<item
android:id="#+id/menu_about"
android:title="#string/menu_about"
android:showAsAction="never"/>
</menu>
-----------------------------------------
METHOD 2:
Add this to onCreate in WebViewActivity.java:
menu_home_button.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
// Menu text
final String[] items = {"Home", "How To", "Rate", "About"};
// Menu Icons in Drawable
final Drawable[] item_icons = {
getResources().getDrawable(R.drawable.home_icon),
getResources().getDrawable(R.drawable.how_to_icon),
getResources().getDrawable(R.drawable.rate_icon),
getResources().getDrawable(R.drawable.about_icon),
};
ListAdapter adapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.custom_menu_dialog, items) {
ViewHolder holder;
class ViewHolder {
ImageView icon;
TextView title;
}
public View getView(int position, View convertView, ViewGroup parent) {
final LayoutInflater inflater = (LayoutInflater)getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.custom_menu_dialog, null);
holder = new ViewHolder();
holder.icon = (ImageView) convertView.findViewById(R.id.icon);
holder.title = (TextView) convertView.findViewById(R.id.title);
convertView.setTag(holder);
} else {
// view already defined, retrieve view holder
holder = (ViewHolder) convertView.getTag();
}
holder.title.setText(items[position]);
holder.icon.setImageDrawable(item_icons[position]);
return convertView;
}
};
Toast.makeText(getApplicationContext(), "Long Press works...", Toast.LENGTH_SHORT).show();
AlertDialog.Builder menu_dialog = new AlertDialog.Builder(WebViewActivity.this);
menu_dialog.setTitle(getResources().getString("My Menu Name");
menu_dialog.setAdapter(adapter, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
//Toast.makeText(WebViewActivity.this, "You selected: " + items[item], Toast.LENGTH_LONG).show();
switch (item) {
case 0:
open_home();
break;
case 1: // HOW TO
open_how_to();
break;
case 2:
open_rate();
break;
case 3: // ABOUT
open_about();
break;
default: // Do Case 0
open_home();
break;
}
dialog.dismiss();
}
});
AlertDialog alert = menu_dialog.create();
alert.show();
return true;
}
});
Finally here is the custom_menu_dialog.xml file with the base info for the text and icon of the menu:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/icon"
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_gravity="center"
android:paddingLeft="16dp"/>
<TextView
android:id="#+id/title"
android:text=""
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#fff6f6f6"
android:textSize="18sp"
android:paddingLeft="16dp"
android:paddingTop="12dp"
android:paddingBottom="12dp"/>
</LinearLayout>
Hopw this helps at least one other person out. It certainly works for me.