on item click in array of string - java

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..

Related

How do I implement SearchView with no errors

I am a beginner and new to coding. I have a problem with ListView in Android Studio. I have created a simple activity with a simple Listview. The Listview contains locations, and when the user clicks on an item the app will open google maps and takes the user to that location. The problem occurred when I implemented a SearchView. When search is applied, whatever result is filtered it will always open the first location. So could you please help me with that. Thanks.
This is my code and sorry for the mess.
MainActivity.java
import com.example.myapplicationsecond.R;
public class MainActivity9 extends AppCompatActivity {
ListView listView;
String[] name = {"First Location","Second Location","Third Location","Fourth Location",};
ArrayAdapter<String> arrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main9);
View view = getLayoutInflater().inflate(R.layout.abs_layout, null);
ActionBar.LayoutParams params = new ActionBar.LayoutParams(
ActionBar.LayoutParams.WRAP_CONTENT,
ActionBar.LayoutParams.MATCH_PARENT,
Gravity.CENTER);
TextView Title = (TextView) view.findViewById(R.id.actionbar_title);
Title.setText("Search Here");
getSupportActionBar().setCustomView(view,params);
getSupportActionBar().setDisplayShowCustomEnabled(true); //show custom title
getSupportActionBar().setDisplayShowTitleEnabled(false); //hide the default title
getSupportActionBar().setTitle("Search Here");
listView = findViewById(R.id.listview);
arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,name);
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(position==0){
Intent intent = new Intent(Intent.ACTION_VIEW , Uri.parse("geo: 21.422458, 39.826213"));
startActivity(intent);
}
if(position==1){
Intent intent = new Intent(Intent.ACTION_VIEW , Uri.parse("geo: 24.467275, 39.610629"));
startActivity(intent);
}
if(position==2){
Intent intent = new Intent(Intent.ACTION_VIEW , Uri.parse("geo: 25.173059, 45.142079"));
startActivity(intent);
}
if(position==3){
Intent intent = new Intent(Intent.ACTION_VIEW , Uri.parse("geo: 26.348400, 43.766664"));
startActivity(intent);
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu,menu);
MenuItem menuItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) menuItem.getActionView();
searchView.setQueryHint("Search Here");
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
arrayAdapter.getFilter().filter(newText);
return false;
}
});
return super.onCreateOptionsMenu(menu);
}
}
MainActivity.Xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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"
tools:context=".MainActivity9">
<ListView
android:id="#+id/listview"
android:textDirection="locale"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
thats how you coded it, you have if(position==0) so no matter what will be on first position you will open same geo:. you should check WHAT is on first position when clicked, so inside onItemClick put:
String clickedText = arrayAdapter.getItem(position);
then find position of this item in all-items array
int positionInArray = java.util.Arrays.asList(name).indexOf(clickedText);
and now use positionInArray for your is else
but thats a quick fix, you should have some model, your custom class with two variables, String name and String geoUri or two longs for lat and lng

Changing text evertime user presses the button using textview

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).

Header ImageView in Navigation Drawer - Android Eclipse

I have created a Navigation Drawer and then I want to put an image header without having it to be part of the item resources. I have created a header image but it was clickable and the id of it was the id of the first item. And the header image become a big header in my whole app which can be seen in every page. How can I fix this.
This is the main activity
public class MainActivity extends Activity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
// Boolean keepPlaying = true;
// MediaPlayer mp;
Item btnplay;
MediaPlayer mp;
private boolean isPaused=false;
private int length;
// nav drawer title
private CharSequence mDrawerTitle;
// used to store app title
private CharSequence mTitle;
// slide menu items
private String[] navMenuTitles;
private TypedArray navMenuIcons;
private ArrayList<NavDrawerItem> navDrawerItems;
private NavDrawerListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mp = new MediaPlayer();
mp.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer arg0) {
// TODO Auto-generated method stub
isPlaying = false;
isPaused = false;
}
});
play(null);//you are calling play by launching
mTitle = mDrawerTitle = getTitle();
// load slide menu items
navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
// nav drawer icons from resources
navMenuIcons = getResources()
.obtainTypedArray(R.array.nav_drawer_icons);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.list_slidermenu);
navDrawerItems = new ArrayList<NavDrawerItem>();
// adding nav drawer items to array
// Search
navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1)));
// Home
navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1)));
// History
navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceId(2, -1)));
// Linux Distro
navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons.getResourceId(3, -1)));
// Dos Vs Linux
navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons.getResourceId(4, -1)));
// Linux Commands
navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, -1)));
// Bash Commands
navDrawerItems.add(new NavDrawerItem(navMenuTitles[6], navMenuIcons.getResourceId(6, -1)));
// Terminal
navDrawerItems.add(new NavDrawerItem(navMenuTitles[7], navMenuIcons.getResourceId(7, -1)));
// About US
navDrawerItems.add(new NavDrawerItem(navMenuTitles[8], navMenuIcons.getResourceId(8, -1)));
// Help
navDrawerItems.add(new NavDrawerItem(navMenuTitles[9], navMenuIcons.getResourceId(9, -1)));
// Recycle the typed array
navMenuIcons.recycle();
mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
// setting the nav drawer list adapter
adapter = new NavDrawerListAdapter(getApplicationContext(),
navDrawerItems);
//Header of the listview, go to header.xml to customize
View header = getLayoutInflater().inflate(R.layout.header_navi, null);
//addHeaderView is to add custom content into first row
mDrawerList.addHeaderView(header);
mDrawerList.setAdapter(adapter);
// enabling action bar app icon and behaving it as toggle button
getActionBar().setDisplayHomeAsUpEnabled(false);
getActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer_invisible, //nav menu toggle icon
R.string.app_name, // nav drawer open - description for accessibility
R.string.app_name // nav drawer close - description for accessibility
) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
// calling onPrepareOptionsMenu() to show action bar icons
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
// calling onPrepareOptionsMenu() to hide action bar icons
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
// on first time display view for first nav item
displayView(1);
}
}
/**
* Slide menu item click listener
* */
private class SlideMenuClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// display view for selected nav drawer item
displayView(position);
}
}
//inflate items in actionbar
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
//Background sounds
boolean isPlaying = false;
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// toggle nav drawer on selecting action bar app icon/title
mDrawerToggle.onOptionsItemSelected(item);
if (item.getItemId() == R.id.btnplay) //whatever you named in xml
{
invalidateOptionsMenu();
}
return super.onOptionsItemSelected(item);
}
public void play(MenuItem menuItem) {
if (!isPlaying && !isPaused) {
mp = new MediaPlayer();
/* Toast.makeText(getApplicationContext(), "play started",
Toast.LENGTH_SHORT).show();
*/
try {
AssetFileDescriptor afd = getAssets().openFd("bgmusic_mainactivity.ogg");
mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(),
afd.getLength());
mp.prepare();
mp.start();// play sound
mp.setLooping(true);
} catch (Exception e) {
e.printStackTrace();
}
isPlaying = true;
} else if (isPlaying) {
/* Toast.makeText(getApplicationContext(), "play paused",
Toast.LENGTH_SHORT).show();
*/
mp.pause();
isPlaying = false;
isPaused = true;
length = mp.getCurrentPosition();
menuItem.setIcon(R.drawable.ic_action_volume_muted);
// and for resuming the player from the position where it stopped
// lately is done by:
} else if (isPaused) {
mp.seekTo(length);
mp.start();
isPlaying = true;
isPaused = false;
menuItem.setIcon(R.drawable.ic_action_volume_on);
}
}
/***
* Called when invalidateOptionsMenu() is triggered
*/
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
if(isPlaying){
menu.getItem(0).setIcon(R.drawable.ic_action_volume_on);
}
else{
menu.getItem(0).setIcon(R.drawable.ic_action_volume_muted);
}
return super.onPrepareOptionsMenu(menu);
}
/**
* Displaying fragment view for selected nav drawer list item
* */
private void displayView(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
switch (position) {
case 0:
fragment = new CommandList();
break;
case 1:
fragment = new Home();
break;
case 2:
fragment = new History();
break;
case 3:
fragment = new LinuxDistro();
break;
case 4:
fragment = new DosLinux();
break;
case 5:
fragment = new LinuxCommands();
break;
case 6:
fragment = new BashCommands();
break;
case 7:
fragment = new Terminal();
break;
case 8:
fragment = new AboutUs();
break;
case 9:
fragment = new Help();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(navMenuTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment!");
}
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
/**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggls
mDrawerToggle.onConfigurationChanged(newConfig);
}
// exit dialog
#Override
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you really want to close the app?")
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Tux To Go Alert!")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
mp.stop();
finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
header_navi.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/header"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<ImageView
android:id="#+id/img_header"
android:layout_width="fill_parent"
android:layout_height="200dp"
android:scaleType="fitXY"
android:src="#drawable/header" />
</RelativeLayout>
activity_main
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/view"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v4.widget.DrawerLayout
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/header"
>
<!-- Framelayout to display Fragments -->
<FrameLayout
android:id="#+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
<!-- Listview to display slider menu -->
<ListView
android:id="#+id/list_slidermenu"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#color/list_divider"
android:dividerHeight="1dp"
android:listSelector="#drawable/list_selector"
android:background="#color/list_background"/>
</android.support.v4.widget.DrawerLayout>
</RelativeLayout>
There is A simple way to add a image or Header in the Navigation :
you can add any View or image view in the "DrawerLayout" just put your list-view in a "LinearLayout" and add a Image view and the list view in that Layout. It will show the Image View or any other view which you added in the "DrawerLayout" .
As Example :
<android.support.v4.widget.DrawerLayout
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/header"
>
<!-- Framelayout to display Fragments -->
<FrameLayout
android:id="#+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
<LinearLayout
android:id="#+id/header"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<ImageView
android:id="#+id/img_header"
android:layout_width="fill_parent"
android:layout_height="200dp"
android:scaleType="fitXY"
android:src="#drawable/header" />
<!-- Listview to display slider menu -->
<ListView
android:id="#+id/list_slidermenu"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#color/list_divider"
android:dividerHeight="1dp"
android:listSelector="#drawable/list_selector"
android:background="#color/list_background"/>
</LinearLayout>
</android.support.v4.widget.DrawerLayout>
Just put your <ListView> and <ImageView> in a <RelativeLayout> and add this to <ListView>
android:layout_below="your image id"
Replace your image id with image id.

Open Actionbar Menu on Longclick - Android

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.

How to show value of EditText in listview each time on button click in android

I have two EditText fields i.e name and marks and one Add button.
I have to display EditText values each and every time whenever Add button is clicked.
However,I am only able to display only one single value on listview.
When i clicked again on Add button,its previous value get erased and newer value gets displayed in listview.
I wanna populate whole list in listview.
public class MainActivity extends Activity {
EditText name1;
EditText marks1;
private ListView lv;
ArrayAdapter<String> aa;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
TextView markshee = (TextView)findViewById(R.id.textView3);
markshee.setText("");
Button btnAdd = (Button) findViewById(R.id.button1);
btnAdd.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
try{
name1 = (EditText)findViewById(R.id.editText1);
String name = name1.getText().toString();
marks1 = (EditText)findViewById(R.id.editText2);
String marks = marks1.getText().toString();
if(name.equals("") || marks.equals("")){
String str="Don't Leave any field blank !";
Toast toast = Toast.makeText(MainActivity.this, str, Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
else {
TextView marksheet = (TextView)findViewById(R.id.textView3);
marksheet.setText("Marks Sheet");
marksheet.setTextColor(Color.BLUE);
TextView nam = (TextView)findViewById(R.id.textView4);
nam.setText("Name");
nam.setTextColor(Color.RED);
TextView mar = (TextView)findViewById(R.id.textView5);
mar.setText("Marks");
mar.setTextColor(Color.RED);
name1.setText("");
marks1.setText("");
lv = (ListView) findViewById(R.id.listView1);
lv.setItemsCanFocus(true);
ArrayList<String> data = new ArrayList<String>();
data.add(" "+name+" "+marks);
aa =
new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1, data);
lv.setAdapter(aa);
}
}catch(Exception ex)
{
System.out.println(ex.getStackTrace());
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
Try this:
you declare ArrayList is public otherwise it will create each and every time clicking and sotre last items only
public class MainActivity extends Activity {
EditText name1;
EditText marks1;
private ListView lv;
ArrayAdapter<String> aa;
ArrayList<String> data = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
TextView markshee = (TextView)findViewById(R.id.textView3);
markshee.setText("");
Button btnAdd = (Button) findViewById(R.id.button1);
btnAdd.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
try{
name1 = (EditText)findViewById(R.id.editText1);
String name = name1.getText().toString();
marks1 = (EditText)findViewById(R.id.editText2);
String marks = marks1.getText().toString();
if(name.equals("") || marks.equals("")){
String str="Don't Leave any field blank !";
Toast toast = Toast.makeText(MainActivity.this, str, Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
else {
TextView marksheet = (TextView)findViewById(R.id.textView3);
marksheet.setText("Marks Sheet");
marksheet.setTextColor(Color.BLUE);
TextView nam = (TextView)findViewById(R.id.textView4);
nam.setText("Name");
nam.setTextColor(Color.RED);
TextView mar = (TextView)findViewById(R.id.textView5);
mar.setText("Marks");
mar.setTextColor(Color.RED);
name1.setText("");
marks1.setText("");
lv = (ListView) findViewById(R.id.listView1);
lv.setItemsCanFocus(true);
data.add(" "+name+" "+marks);
aa =
new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1, data);
lv.setAdapter(aa);
}
}catch(Exception ex)
{
System.out.println(ex.getStackTrace());
}
}
});
}
Instead of creating and initializing your data inside onClick, try initializing it in the onCreate method and inside onClick just add the new entry to it:
ArrayList<String> data = new ArrayList<String>();
Button btnAdd = (Button) findViewById(R.id.button1);
btnAdd.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v) {
.....
.....
.....
data.add(" "+name+" "+marks);
....
}
}
With your existing code, when your onClick method is called, you are creating a new list data every time and adding just a single entry to it, hence it displays only a single value.
UPDATE:
Lets see an example :
Lets say have a class from which I need to get incremental value on calling a method getIncrementValue that should return current value +1 every time I call it.
This is the code for it:
public class MyClass{
public int getIncrementValue(){
int a = 0;
a = a+1;
return a;
}
}
Now if I call this method like:
MyClass m = new MyClass();
System.out.println(m.getIncrementValue()); //prints 1
System.out.println(m.getIncrementValue()); //prints 1 should print 2 right
System.out.println(m.getIncrementValue()); //prints 1 should print 3 right
You see this, every time it prints only one value instead of incremented value.
This is beacuse every time I call getIncrementValue(), I am declaring and initializing a new variable a = 0 and incrementing it and returning it, hence every time it increments it to 1 and return 1 (instead of 2 and three and so on)
For this I need to change slighlty my class, declare variable a outside that method make it a class variable (in your case declare ArrayList<String> data = new ArrayList<String>(); just after the line ArrayAdapter<String> aa;)
public class MyClass{
int a = 0;
public int getIncrementValue(){
a = a+1;
return a;
}
}
Now if I call this method like:
MyClass m = new MyClass();
System.out.println(m.getIncrementValue()); //prints 1
System.out.println(m.getIncrementValue()); //prints 2 should print 2 right
System.out.println(m.getIncrementValue()); //prints 3 should print 3 right
Now you can uderstand why that happens with your code.
So try tweaking your code a little bit and it will be fine.
according to your question i have done something for you.. i have created two Edit text as name and marks and created two lists name as list and list2...and one add button... for run this code your min sdk version should be 11.. otherwise it will not work....when you enter value on edit text box and click on add button these value will be show on two different list and never erased the previous value..... follow my code...
MainActivity.java
package com.example.textview;
import java.util.ArrayList;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
public class MainActivity extends Activity {
EditText Name, Marks;
Button Add;
ListView lv, lv2;
ArrayList<String> list = new ArrayList<String>();
ArrayAdapter<String> adapter;
ArrayList<String> list2 = new ArrayList<String>();
ArrayAdapter<String> adapter2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Name=(EditText)findViewById(R.id.name);
Marks=(EditText)findViewById(R.id.marks);
Add=(Button)findViewById(R.id.add);
lv=(ListView)findViewById(R.id.list);
lv2=(ListView)findViewById(R.id.list2);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);
lv.setAdapter(adapter);
adapter2 = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_activated_1, list2);
lv2.setAdapter(adapter2);
Add.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
String name = Name.getText().toString();
String marks = Marks.getText().toString();
if(name.length() > 0 && marks.length() > 0)
{
list.add(name);
adapter.notifyDataSetChanged();
list2.add(marks);
adapter2.notifyDataSetChanged();
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
activity_main.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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_toLeftOf="#+id/textView2" >
</ListView>
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/list"
android:layout_marginTop="36dp"
android:text="Enter name"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="#+id/name"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/list"
android:layout_alignRight="#+id/textView1"
android:layout_below="#+id/textView1"
android:layout_marginTop="15dp"
android:ems="10"
android:inputType="textPersonName" >
<requestFocus />
</EditText>
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/textView1"
android:layout_alignBottom="#+id/textView1"
android:layout_marginLeft="28dp"
android:layout_toRightOf="#+id/textView1"
android:text="Enter marks"
android:textAppearance="?android:attr/textAppearanceMedium" />
<ListView
android:id="#+id/list2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/textView1"
android:layout_alignLeft="#+id/textView2"
android:layout_alignParentTop="true"
android:layout_alignRight="#+id/textView2" >
</ListView>
<EditText
android:id="#+id/marks"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/name"
android:layout_alignLeft="#+id/textView2"
android:layout_alignRight="#+id/textView2"
android:ems="10" />
<Button
android:id="#+id/add"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/name"
android:layout_marginTop="33dp"
android:layout_toRightOf="#+id/name"
android:text="ADD" />
</RelativeLayout>
and your min sdk version should be 11

Categories