Creating a multi leveled listview application - android

So here is the code. Its pretty self explanatory. The only problem I am having is retaining the value for int level. Its lost every time. I need the value to be retained and it will work. This is a snapshot. It should be extensible to as many levels deep and as many items per level.
XML code:
<RelativeLayout 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"
tools:context=".MainActivity" >
<ListView
android:id="#+id/listView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" >
</ListView>
</RelativeLayout>
Java code:
package com.example.kjkjsdkjdsjkdfs;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class MainActivity extends ListActivity {
String categoryselected = "main";
public int level = 0;
#SuppressWarnings("null")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] array;
Intent received = getIntent();
// Setup as main ListView
if (received == null || !received.hasExtra("array")) {
array = new String[] { "1", "2", "3" };
}
// Setup as sub ListView
else {
array = received.getStringArrayExtra("array");
}
if(received != null || !received.hasExtra("level")) {
level = received.getIntExtra("level", 0);
}
setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, array));
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
level = level + 1;
Intent starting = new Intent(MainActivity.this, MainActivity.class);
switch (level) {
case 1:
switch (position) {
case 0:
starting.putExtra("array", new String[] { "1a", "1b", "1c" });
starting.putExtra("level", level);
break;
case 1:
starting.putExtra("array", new String[] { "2a", "2b", "2c" });
starting.putExtra("level", level);
break;
case 2:
starting.putExtra("array", new String[] { "3a", "3b", "3c" });
starting.putExtra("level", level);
break;
}
break;
case 2:
switch (position) {
case 0:
starting.putExtra("array", new String[] { "1aa", "1ab" });
starting.putExtra("level", level);
break;
}
break;
case 3:
switch (position) {
case 0:
starting.putExtra("array", new String[] { "1aaa", "1aab" });
starting.putExtra("level", level);
break;
}
break;
}
startActivity(starting);
}
#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;
}
}

Update your code like this :
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class ListItems extends ListActivity {
String categoryselected = "main";
public int level = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] array;
Intent received = getIntent();
// Setup as main ListView
if (received == null || !received.hasExtra("array")) {
array = new String[] { "1", "2", "3" };
}
// Setup as sub ListView
else {
array = received.getStringArrayExtra("array");
}
if(received != null || !received.hasExtra("level")) {
level = received.getIntExtra("level", 0);
}
setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, array));
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
level = level + 1;
Intent starting = new Intent(ListItems.this, ListItems.class);
switch (level) {
case 1:
switch (position) {
case 0:
starting.putExtra("array", new String[] { "1a", "1b", "1c" });
starting.putExtra("level", level);
break;
case 1:
starting.putExtra("array", new String[] { "2a", "2b", "2c" });
starting.putExtra("level", level);
break;
case 2:
starting.putExtra("array", new String[] { "3a", "3b", "3c" });
starting.putExtra("level", level);
break;
}
break;
case 2:
switch (position) {
case 0:
starting.putExtra("array", new String[] { "1aa", "1ab" });
starting.putExtra("level", level);
break;
}
break;
case 3:
switch (position) {
case 0:
starting.putExtra("array", new String[] { "1aaa", "1aab" });
starting.putExtra("level", level);
break;
}
break;
}
startActivity(starting);
}
#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;
}
}

Related

In ListView make the first item as a title ,and index issue

I am trying to display the title for the Navigation Drawer,It displayed properly but the problem is that when I am trying to click on the first item in the navigation drawer that is home ,it will display the Queues.class instead of expected class.And when click on the last item in the navigation Drawer application get crash.I just want to Display the Title in the navigation Drawer and last item click will show proper activity.Also problem is that the title display two times.
package com.abc;
//import android.app.Activity;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.R.*;
import android.app.ActionBar;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.BaseBundle;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class navigation_drawer_class extends Activity
//public class navigation_drawer_class extends ListActivity
{
private static final int Copy = 0;
int a =0;
public static FrameLayout frameLayout;
TextView mytextview;
public static ListView mDrawerList;
public DrawerLayout mDrawerLayout;
String Fullname;
protected String[] listArray = {"Home","Queue","Inbox","Create Ticket","Search","Clients","App settings"};
protected static int position;
private static boolean isLaunch = true;
//*****************************************
JSONObject post_details_obj,post_obj;
public static String FIRST_NAME="first_name",LAST_NAME="last_name";
JSONArray staff_data_array;
//*****************************************
private ActionBarDrawerToggle actionBarDrawerToggle;
Operation op=new Operation();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//------------------ THIS ONE -------------------------
getActionBar().setHomeAsUpIndicator(R.drawable.crop3);//THIS ONE FOR THE DRAWER LOGO
//--------------------- THIS ONE ----------------------
frameLayout = (FrameLayout)findViewById(R.id.content_frame);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
/// mDrawerList.setAdapter(null);
//***************** To Set the Welcome client ******************************************
//========= THIS ONE ===============
new getname().execute();
//========= THIS ONE ===============
/* mDrawerList.setAdapter(null);
View header = (View)getLayoutInflater().inflate(R.layout.headerview,null);
TextView headerValue = (TextView) header.findViewById(R.id.headerview_id);
headerValue.setText("Mydata");
mDrawerList.addHeaderView(header, null, false);//addHeaderView(header, null, false)
*/
/* TextView tv=new TextView(getApplicationContext());
Log.d("Fullname in oncreate : ",Fullname.toString());
tv.setText(Fullname); */
//******************To Set the Welcome client ******************************************
mDrawerList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listArray));
mDrawerList.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
openActivity(position);
}
});
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
actionBarDrawerToggle = new ActionBarDrawerToggle(
this, // host Activity
mDrawerLayout, // DrawerLayout object
R.drawable.ic_launcher, // nav drawer image to replace 'Up' caret
R.string.open_drawer, // "open drawer" description for accessibility
R.string.close_drawer) // "close drawer" description for accessibility
{
#Override
public void onDrawerClosed(View drawerView)
{
getActionBar().setTitle(listArray[position]);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
super.onDrawerClosed(drawerView);
}
#Override
public void onDrawerOpened(View drawerView)
{
getActionBar().setTitle(getString(R.string.app_name));
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
super.onDrawerOpened(drawerView);
}
#Override
public void onDrawerSlide(View drawerView, float slideOffset)
{
super.onDrawerSlide(drawerView, slideOffset);
}
#Override
public void onDrawerStateChanged(int newState)
{
super.onDrawerStateChanged(newState);
}
};
mDrawerLayout.setDrawerListener(actionBarDrawerToggle);
if(isLaunch){
isLaunch = false;
openActivity(0);
}
}
protected void openActivity(int position) {
// mDrawerList.setItemChecked(position, true);
// setTitle(listArray[position]);
mDrawerLayout.closeDrawer(mDrawerList);
navigation_drawer_class.position = position; //Setting currently selected position in this field so that it will be available in our child activities.
switch (position) {
case 0:
startActivity(new Intent(this, Folders.class));
break;
//case 2:
case 1:
Intent i=new Intent(navigation_drawer_class.this,Queues.class);
i.putExtra("set_queue","set");
startActivity(i);
break;
case 2:
//case 3:
Intent inbox=new Intent(navigation_drawer_class.this,Tickets.class);
inbox.putExtra("filter_id","&vis_filter_id=1");
inbox.putExtra("title","Inbox");
inbox.putExtra("set_queue","no");
startActivity(inbox);
break;
case 3:
//case 4:
startActivity(new Intent(this, New_Ticket_step1.class));
break;
case 4:
//case 5:
startActivity(new Intent(this, Search.class));
break;
case 5:
//case 6:
startActivity(new Intent(this, Client.class));
break;
case 6:
//case 7:
startActivity(new Intent(this, Settings.class));
break;
default:
break;
}
/*
switch (position) {
case 0:
break;
case 1:
startActivity(new Intent(this, Folders.class));
break;
case 2:
Intent i=new Intent(navigation_drawer_class.this,Queues.class);
i.putExtra("set_queue","set");
startActivity(i);
break;
case 3:
Intent inbox=new Intent(navigation_drawer_class.this,Tickets.class);
inbox.putExtra("filter_id","&vis_filter_id=1");
inbox.putExtra("title","Inbox");
inbox.putExtra("set_queue","no");
startActivity(inbox);
break;
case 4:
startActivity(new Intent(this, New_Ticket_step1.class));
break;
case 5:
startActivity(new Intent(this, Search.class));
break;
case 6:
startActivity(new Intent(this, Client.class));
break;
case 7:
startActivity(new Intent(this, Settings.class));
break;
default:
break;
}
*/
//Toast.makeText(this, "Selected Item Position::"+position, Toast.LENGTH_LONG).show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// getMenuInflater().inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
// The action bar home/up action should open or close the drawer.
// ActionBarDrawerToggle will take care of this.
if (actionBarDrawerToggle.onOptionsItemSelected(item))
{
return true;
}
switch (item.getItemId())
{
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public boolean onPrepareOptionsMenu(Menu menu)
{
//boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
//menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
/* We can override onBackPressed method to toggle navigation drawer*/
#Override
public void onBackPressed()
{
if(mDrawerLayout.isDrawerOpen(mDrawerList))
{
mDrawerLayout.closeDrawer(mDrawerList);
}
else
{
mDrawerLayout.openDrawer(mDrawerList);
}
}
//-----------------------------------------------------------
private class getname extends AsyncTask<Void, Void, JSONArray>
{
Dialog dialog;
#Override
public void onPreExecute()
{
dialog = new Dialog(navigation_drawer_class.this,android.R.style.Theme_Translucent_NoTitleBar);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.progressbar);
dialog.show();
}
#Override
protected JSONArray doInBackground(Void... params)
{
String STAFF_URL=op.getUrl(getApplicationContext(),"staff","get_staff_details","");
staff_data_array = JSONfunctions.getJSONfromURL(STAFF_URL+"&vis_encode=json",navigation_drawer_class.this);
return staff_data_array;
}
#Override
public void onPostExecute(JSONArray staff_data_array)
{
super.onPostExecute(staff_data_array);
String staff_data_result =staff_data_array.toString();
try {
post_obj = staff_data_array.getJSONObject(0);
String fname=post_obj.getString(FIRST_NAME);
String lname=post_obj.getString(LAST_NAME);
//Fullname =fname+" "+lname;
Fullname =fname;
if(Fullname=="")
{
Fullname="Admin";
}
Fullname="Welcome "+Fullname;
View header = (View)getLayoutInflater().inflate(R.layout.headerview,null);
TextView headerValue = (TextView) header.findViewById(R.id.headerview_id);
headerValue.setText(Fullname);
mDrawerList.addHeaderView(header, null, false);//addHeaderView(header, null, false) */
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
dialog.dismiss();
}
}
//-----------------------------------------------------------
}

Navigation Drawer and ViewPager conflict

I'm currently developing an android application where I'm using a navigation drawer as well as the swipe gesture using viewPager to traverse through fragments.
Basically, I want the user to be able to select pages (fragments) using the navigation drawer and be able to swipe to the next page (fragment).
My problem right now is that they overlap. The swipe gesture works as expected but when I select another page on the nav drawer they underlying page doesn't disappear. I need someway to "refresh" each fragment.
Here is my code in the MainActivity.java page
package com.example.home.cloud;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity implements FragmentDrawer.FragmentDrawerListener {
private static String TAG = MainActivity.class.getSimpleName();
private static final int NUM_PAGES = 10;
private Toolbar mToolbar;
private FragmentDrawer drawerFragment;
private ViewPager mPager;
private PagerAdapter mPagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mPager = (ViewPager) findViewById(R.id.pager);
mPagerAdapter = new MyFragmentStatePagerAdapter(getSupportFragmentManager());
mPager.setAdapter(mPagerAdapter);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
drawerFragment = (FragmentDrawer)
getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
drawerFragment.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), mToolbar);
drawerFragment.setDrawerListener(this);
// display the first navigation drawer view on app launch
displayView(0);
}
#Override
public void onBackPressed() {
if (mPager.getCurrentItem() == 0) {
super.onBackPressed();
} else {
mPager.setCurrentItem(mPager.getCurrentItem() - 1);
}
}
private class MyFragmentStatePagerAdapter extends FragmentStatePagerAdapter
{
public MyFragmentStatePagerAdapter(FragmentManager fm)
{
super(fm);
}
#Override
public Fragment getItem(int position) {
final Fragment result;
switch (position) {
case 0:
result= new HomeFragment();
break;
case 1:
result= new OverviewFragment();
break;
case 2:
result= new BenFragment();
break;
case 3:
result= new TechFragment();
break;
case 4:
result= new ArcFragment();
break;
case 5:
result= new DmodFragment();
break;
case 6:
result= new SmodFragment();
break;
case 7:
result= new VirtFragment();
break;
case 8:
result= new StorageFragment();
break;
case 9:
result= new SecurityFragment();
break;
default: result=null;
break;
}
/* if (result != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container_body, result);
fragmentTransaction.commit();
}*/
return result;
}
#Override
public int getCount() {
return NUM_PAGES;
}
}
#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;
}
if(id == R.id.action_search){
Toast.makeText(getApplicationContext(), "Search action is selected!", Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onDrawerItemSelected(View view, int position) {
displayView(position);
}
private void displayView(int position) {
Fragment fragment = null;
String title = getString(R.string.app_name);
switch (position) {
case 0:
fragment = new HomeFragment();
title = getString(R.string.title_home);
break;
case 1:
fragment = new OverviewFragment();
title = getString(R.string.title_overview);
break;
case 2:
fragment=new BenFragment();
title="Benefits and Risks";
break;
case 3:
fragment=new TechFragment();
title="Technologies behind Cloud Computing";
break;
case 4:
fragment = new ArcFragment();
title="Architecture";
break;
case 5:
fragment= new DmodFragment();
title="Deployment Models";
break;
case 6:
fragment = new SmodFragment();
title="Service Models";
break;
case 7:
fragment = new VirtFragment();
title="Virtualization";
break;
case 8:
fragment = new StorageFragment();
title="Data Storage";
break;
case 9:
fragment = new SecurityFragment();
title="Security";
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container_body, fragment);
fragmentTransaction.commit();
// set the toolbar title
getSupportActionBar().setTitle(title);
}
}
}
The trouble is that you're displaying your fragments in two different ways. Your displayView() method is creating new fragments and displaying them, rather than showing the ones which are already loaded in the ViewPager. To fix this, you need displayView() to instead set your ViewPager position.
private void displayView(int position) {
mPager.setCurrentItem(position);
getSupportActionBar().setTitle(mPagerAdapter.getPageTitle(position));
}

Controlling which fragment is shown from navDrawer

I am working on this application that has a viewPager and a few swipeable fragments in its MainActivity. Today I implemented navigation drawer but I do not know how to control which fragment is shown from drawer`s DrawerItemClickListener class. Is there a solution or I was just moving in a wrong direction and have to change the way navigation drawer is implemented?
Tutorial suggests to use the getFragmentManager method which does not work for me.
Thanks.
Here is DrawerItemClickListener class:
package com.freestylers.druskischool;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.AdapterView;
public class DrawerItemClickListener implements ListView.OnItemClickListener
{
public int FragmentNumber;
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long
id) {
selectItem(position);
}
private void selectItem(int position) {
Fragment fragment = null;
switch (position) {
case 0:
fragment = new StartFragment();
FragmentNumber=0;
break;
case 1:
fragment = new MesFragment();
FragmentNumber=1;
break;
case 2:
fragment = new NaujienosFragment();
FragmentNumber=2;
break;
case 3:
fragment = new InstruktoriaiFragment();
FragmentNumber=3;
break;
case 4:
fragment = new MetodikaFragment();
FragmentNumber=4;
break;
case 5:
fragment = new GalerijaFragment();
FragmentNumber=5;
break;
case 6:
fragment = new InstruktoriaiFragment();
FragmentNumber=6;
break;
case 7:
fragment = new AtsiliepimaiFragment();
FragmentNumber=7;
break;
case 8:
fragment = new DrufunparkFragment();
FragmentNumber=8;
break;
case 9:
FragmentNumber=9;
fragment = new KontaktaiFragment();
break;
default:
break;
}
if (fragment != null) {
//tutorial suggests this code:
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
getActionBar().setTitle(mNavigationDrawerItemTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
Log.e("MainActivity", "Error in creating fragment");
}
}
}
And here is my MainActivity.java:
package com.freestylers.druskischool;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBarDrawerToggle;
public class MainActivity extends ActionBarActivity {
private String[] mNavigationDrawerItemTitles;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
ActionBarDrawerToggle mDrawerToggle;
ViewPager pager;
FragmentStatePagerAdapter adapter2;
/* Just some random URLs
*
* Each page of our pager will display one URL from this array
* Swiping, to the right will take you to the next page having
* the next URL.
*/
String[] fragments={
"start",
"mes",
"naujienos",
"instruktoriai",
"metodika",
"galerija",
"kainos",
"atsiliepimai",
"drufunpark",
"kontaktai"
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ObjectDrawerItem[] drawerItem = new ObjectDrawerItem[10];
drawerItem[0] = new ObjectDrawerItem(R.drawable.ic_action_copy,
"Pradžia");
drawerItem[1] = new ObjectDrawerItem(R.drawable.ic_action_copy, "Mes");
drawerItem[2] = new ObjectDrawerItem(R.drawable.ic_action_copy,
"Naujienos");
drawerItem[3] = new ObjectDrawerItem(R.drawable.ic_action_copy,
"Instruktoriai");
drawerItem[4] = new ObjectDrawerItem(R.drawable.ic_action_copy,
"Metodika");
drawerItem[5] = new ObjectDrawerItem(R.drawable.ic_action_copy,
"Galerija");
drawerItem[6] = new ObjectDrawerItem(R.drawable.ic_action_copy,
"Kainos");
drawerItem[7] = new ObjectDrawerItem(R.drawable.ic_action_copy,
"Atsiliepimai");
drawerItem[8] = new ObjectDrawerItem(R.drawable.ic_action_copy,
"Drufunpark");
drawerItem[9] = new ObjectDrawerItem(R.drawable.ic_action_copy,
"Kontaktai");
mNavigationDrawerItemTitles=
getResources().getStringArray(R.array.navigation_drawer_items_array);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
DrawerItemCustomAdapter adapter = new DrawerItemCustomAdapter(this,
R.layout.listview_item_row, drawerItem);
mDrawerList.setAdapter(adapter);
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
pager=(ViewPager)findViewById(R.id.my_pager);
adapter2=new FragmentStatePagerAdapter(
getSupportFragmentManager()
){
#Override
public int getCount() {
// This makes sure getItem doesn't use a position
// that is out of bounds of our array of fragments
return fragments.length;
}
#Override
public Fragment getItem(int position) {
// Here is where all the magic of the adapter happens
// As you can see, this is really simple.
//(fragments[position]);
if(position==0){
return StartFragment.newInstance();
}
else if(position==1){
return MesFragment.newInstance();
}
else if(position==2){
return NaujienosFragment.newInstance();
}
else if(position==3){
return InstruktoriaiFragment.newInstance();
}
else if(position==4){
return MetodikaFragment.newInstance();
}
else if(position==5){
return GalerijaFragment.newInstance();
}
else if(position==6){
return KainosFragment.newInstance();
}
else if(position==7){
return AtsiliepimaiFragment.newInstance();
}
else if(position==8){
return DrufunparkFragment.newInstance();
}
else if(position==9){
return KontaktaiFragment.newInstance();
}
else{return KontaktaiFragment.newInstance();}
}
};
//Let the pager know which adapter it is supposed to use
pager.setAdapter(adapter2);
}
#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 super.onCreateOptionsMenu(menu);
}
/*#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();
itu f (id == R.id.action_start) {
return true;
}
return super.onOptionsItemSelected(item);
}*/
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle other action bar items...
/* switch (item.getItemId()) {
case R.id.action_settings:
return true;
}*/
return super.onOptionsItemSelected(item);
}
public static void ChooseFragment(Fragment fragment) {
}
}
I figured out my mistake, it all has to be inside MainActivity.java, DrawerItemClickListener is an inner class.
Still have not found a way to navigate between swipeable fragments from the navDrawer, probably it is impossible.

Unable to imlement drag and drop

I am trying to make a alphabet exam. I have a ImageView11 which shows the a random alphabet which you have to guess. And the imageView_alphabet_image_1 and imageView_alphabet_image_2 will show two options which I have to guess and I will drag the ImageView11 image on correct ImageView which is showing down. But I'm able to do it for only first time when i click on refresh it always showing incorrect toast
<LinearLayout 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:orientation="vertical" >
<Button
android:id="#+id/btn_refresh"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Refresh"/>
<LinearLayout
android:id="#+id/dragLinearLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:orientation="horizontal" >
<ImageView
android:id="#+id/imgView_des"
android:layout_width="70dp"
android:layout_height="80dp"
android:src="#drawable/ic_launcher" />
</LinearLayout>
<LinearLayout
android:id="#+id/bottomLinearLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="150dp"
android:orientation="horizontal"
android:weightSum="1" >
<ImageView
android:id="#+id/imgView_alphabetImage_1"
android:layout_width="70dp"
android:layout_height="80dp"
android:layout_weight="0.25"
android:src="#drawable/a" />
<ImageView
android:id="#+id/imgView_alphabetImage_2"
android:layout_width="70dp"
android:layout_height="80dp"
android:layout_weight="0.25"
android:src="#drawable/a" />
</LinearLayout>
package com.example.cleardoubt;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.DragEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.DragShadowBuilder;
import android.view.View.OnClickListener;
import android.view.View.OnDragListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity implements OnClickListener,
OnTouchListener, OnDragListener {
private ImageView _imgView_des;
private ImageView _imgView_alphabetImage_1;
private ArrayList<Integer> _alphabet_arrayList;
private Button _btn_refresh;
private ImageView _imgView_alphabetImage_2;
private ArrayList<Integer> _tempArrayList;
private ArrayList<Integer> _finalTempArrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initView();
setContentView(R.layout.activity_main);
_imgView_des = (ImageView) findViewById(R.id.imgView_des);
_imgView_des.setOnClickListener(this);
_imgView_des.setOnTouchListener(this);
_imgView_des.setOnDragListener(this);
_imgView_alphabetImage_1 = (ImageView) findViewById(R.id.imgView_alphabetImage_1);
_imgView_alphabetImage_1.setOnClickListener(this);
_imgView_alphabetImage_1.setOnDragListener(this);
_imgView_alphabetImage_2 = (ImageView) findViewById(R.id.imgView_alphabetImage_2);
_imgView_alphabetImage_2.setOnClickListener(this);
_imgView_alphabetImage_2.setOnDragListener(this);
_btn_refresh = (Button) findViewById(R.id.btn_refresh);
_btn_refresh.setOnClickListener(this);
}
private void initView() {
_alphabet_arrayList = new ArrayList<Integer>();
_alphabet_arrayList.add(R.drawable.a);
_alphabet_arrayList.add(R.drawable.b);
_alphabet_arrayList.add(R.drawable.c);
_alphabet_arrayList.add(R.drawable.d);
_alphabet_arrayList.add(R.drawable.e);
_alphabet_arrayList.add(R.drawable.f);
_alphabet_arrayList.add(R.drawable.g);
_tempArrayList = new ArrayList<Integer>();
_finalTempArrayList = new ArrayList<Integer>();
}
#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;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.imgView_des:
break;
case R.id.imgView_alphabetImage_1:
if (_imgView_des
.getDrawable()
.getConstantState()
.equals(_imgView_alphabetImage_1.getDrawable()
.getConstantState())) {
Toast.makeText(this, "matched", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "not matched", Toast.LENGTH_SHORT).show();
}
break;
case R.id.imgView_alphabetImage_2:
if (_imgView_des
.getDrawable()
.getConstantState()
.equals(_imgView_alphabetImage_2.getDrawable()
.getConstantState())) {
Toast.makeText(this, "matched", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "not matched", Toast.LENGTH_SHORT).show();
}
break;
case R.id.btn_refresh:
Random random = new Random();
int index = random.nextInt(7);
_imgView_des.setImageResource(_alphabet_arrayList.get(index));
_imgView_des.setVisibility(View.VISIBLE);
_tempArrayList = (ArrayList<Integer>) _alphabet_arrayList.clone();
_tempArrayList.remove(index);
Collections.shuffle(_tempArrayList, random);
for (int j = 0; j < 1; j++) {
_finalTempArrayList.add(_tempArrayList.get(j));
}
_finalTempArrayList.add(_alphabet_arrayList.get(index));
Collections.shuffle(_finalTempArrayList);
Log.e(" _finalTempArrayList after suffel", _finalTempArrayList.toString());
_imgView_alphabetImage_1.setImageResource(_finalTempArrayList.get(0));
_imgView_alphabetImage_2.setImageResource(_finalTempArrayList.get(1));
_finalTempArrayList.clear();
break;
default:
break;
}
}
#Override
public boolean onTouch(View v, MotionEvent e) {
if (e.getAction() == MotionEvent.ACTION_DOWN) {
// ClipData clipData = ClipData.newPlainText("", "");
DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(v);
v.startDrag(null, shadowBuilder, v, 0);
v.setVisibility(View.INVISIBLE);
return true;
} else {
return false;
}
}
#Override
public boolean onDrag(View v, DragEvent e) {
switch (e.getAction()) {
case DragEvent.ACTION_DRAG_STARTED:
// if (e.getClipDescription().hasMimeType(
// ClipDescription.MIMETYPE_TEXT_PLAIN)) {
// return true;
// } else {
// Toast.makeText(this, "can not accept the image",
// Toast.LENGTH_SHORT).show();
//
// }
// return false;
break;
case DragEvent.ACTION_DROP:
if (_imgView_des
.getDrawable()
.getConstantState()
.equals(_imgView_alphabetImage_1.getDrawable()
.getConstantState())) {
ViewGroup viewGroup = (ViewGroup) v.getParent();
viewGroup.removeView(_imgView_des);
v.setBackground(this.getResources().getDrawable(R.drawable.a));
return true;
}
else if(_imgView_des
.getDrawable()
.getConstantState()
.equals(_imgView_alphabetImage_2.getDrawable()
.getConstantState()))
{
ViewGroup viewGroup = (ViewGroup) v.getParent();
viewGroup.removeView(_imgView_des);
v.setBackground(this.getResources().getDrawable(R.drawable.a));
return true;
}
// else {
// return false;
// }
break;
case DragEvent.ACTION_DRAG_ENDED:
Log.v("a", e.getResult() + "");
if (e.getResult()) {
_imgView_des.setVisibility(View.INVISIBLE);
Log.v("asddd", e.getResult() + "");
Toast.makeText(this, " accept the image",
Toast.LENGTH_SHORT).show();
return true;
} else {
_imgView_des.setVisibility(View.VISIBLE);
Toast toast = new Toast(this);
ImageView view = new ImageView(this);
view.setImageResource(R.drawable.unsuccess);
toast.setView(view);
toast.show();
return true;
}
default:
break;
}
return false;
}
}
I checked you code the problem is in your onDrag method.
case DragEvent.ACTION_DROP event did not call because of you did not return flag case DragEvent.ACTION_DRAG_STARTED: event. You have to pass true flag like below code
case DragEvent.ACTION_DRAG_STARTED:
return true;

Selecting and Deleting List View items dynamically through a CAB on a button click, not through long press

I have an application with a list view and a custom adapter where I add custom objects to the list view. I know how to delete objects through long-pressing one of the list items in the list, but I have a trash can action bar button and I want it so that when you click on that button, it brings up the same CAB as if you were long-pressing a list item, and I want the user to be able to select multiple list items, and then click a delete button on the CAB.
What I have tried:
package viva.inspection.com.inspectionpicker;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.SparseBooleanArray;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AbsListView;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.GregorianCalendar;
import java.util.HashSet;
import java.util.List;
import viva.inspection.com.inspectionpicker.R;
public class ListActivity extends Activity {
private static ArrayList<InspectionItem> inspections;
private static final String s = "inspection list";
public static final String PREFS_NAME = "MyPrefsFile";
ListView inspectionList;
private final int GET_VALUE=111;
private final int GET_VAL = 11;
private MyAdapter listviewadapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
inspectionList = (ListView) findViewById(R.id.listView);
inspectionList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
inspections = new ArrayList<InspectionItem>();
inspections.add(new InspectionItem(new GregorianCalendar(7,15,14), "hi", "hi", "hi", "hi", "hi", "hi", "hi", "hi", "hi", "hi", new ArrayList<String>()));
if(getIntent().getStringExtra("NEW_VALUE") != null) {
//addItems(getIntent().getStringExtra("NEW_VALUE"));
SharedPreferences.Editor edit = settings.edit();
edit.putString("myKey", TextUtils.join(",", inspections));
edit.commit();
}
if(!(settings.getString("myKey", "hi").equals("hi"))) {
//We have saved values. Grab them.
} else {
//We have no saved values
inspections = new ArrayList<InspectionItem>();
inspections.add(new InspectionItem(new GregorianCalendar(7,15,14), "hi", "hi", "hi", "hi", "hi", "hi", "hi", "hi", "hi", "hi", new ArrayList<String>()));
}
listviewadapter = new MyAdapter(this, R.layout.row_layout,
inspections);
inspectionList.setAdapter(listviewadapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.list, 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();
switch(id) {
case R.id.action_settings:
return true;
case R.id.action_new:
Intent intent = new Intent(this, InitialChoose.class);
startActivity(intent);
return true;
case R.id.action_delete:
inspectionList.setOnItemSelectedListener(new ActionBarCallBack());
startActionMode(new ActionBarCallBack());
//mActionMode.finish();
return true;
}
return super.onOptionsItemSelected(item);
}
class ActionBarCallBack implements ListView.OnItemSelectedListener, ActionMode.Callback {
ActionMode activeMode;
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.delete:
// Calls getSelectedIds method from ListViewAdapter Class
SparseBooleanArray selected = listviewadapter
.getSelectedIds();
// Captures all selected ids with a loop
for (int i = (selected.size() - 1); i >= 0; i--) {
if (selected.valueAt(i)) {
InspectionItem selecteditem = listviewadapter
.getItem(selected.keyAt(i));
// Remove selected items following the ids
listviewadapter.remove(selecteditem);
}
}
// Close CAB
mode.finish();
return true;
default:
return false;
}
}
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
mode.getMenuInflater().inflate(R.menu.cab_menu, menu);
return true;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
// TODO Auto-generated method stub
listviewadapter.removeSelection();
}
#Override
public boolean onPrepareActionMode(final ActionMode mode, Menu menu) {
// TODO Auto-generated method stub
return false;
}
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
listviewadapter.toggleSelection(i);
final int checkedCount = inspectionList.getCheckedItemCount();
// Set the CAB title according to total checked items
activeMode.setTitle(checkedCount + " Selected");
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
}
/*
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode==RESULT_OK){
if(requestCode == GET_VALUE){
if(data.getStringExtra("NEW_VALUE")!=null && data.getStringExtra("NEW_VALUE").length()>0){
addItems(data.getStringExtra("NEW_VALUE"));
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor edit = settings.edit();
edit.putString("myKey", TextUtils.join(",", inspections));
edit.commit();
}
}
}
} */
}
Basically, with this code, if I click on the trash-can action bar button, the CAB shows up, but I can't select any items on the list and proceed to delete them. Any help is greatly appreciated.
This is a tricky one. I used CheckedTextView's for multiple selections inside the list however when the list scrolls the adapter re-uses the old views and sometimes checks the wrong items. To overcome that I used an array of all the currently checked items, so the adapter can know which items should be checked.
Before going back to the original list you need to call notifyDataSetChanged(), which notifies to redrawn the visible views therefore uncheck/delete the selections (depends on what action you chose back at the CAB).
package com.example.simon.cabdelete;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.ActionMode;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckedTextView;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Simon on 2014 Jul 18.
*/
public class MainActivity extends Activity {
private final static String TAG = "MainActivity";
MyAdapter mAdapter;
ListView mListView;
List<String> mListArray;
SparseBooleanArray mCheckedItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mListView = (ListView) findViewById(R.id.listView);
// Default list item click listener
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// Do something on normal click
}
});
mCheckedItems = new SparseBooleanArray();
int size = 20;
mListArray = new ArrayList<String>(size);
for (int i=0; i<size; i++)
mListArray.add("Item "+i);
mAdapter = new MyAdapter(this, R.layout.list_item, mListArray);
mListView.setAdapter(mAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.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();
switch (id) {
case R.id.action_settings:
break;
case R.id.action_delete:
startActionMode(new ActionBarCallBack());
break;
}
return super.onOptionsItemSelected(item);
}
public class MyAdapter extends ArrayAdapter<String> {
List<String> items;
int itemResource;
LayoutInflater inflater;
public MyAdapter(Context ctx, int resource, List<String> objects) {
super(ctx, resource, objects);
this.items = objects;
this.itemResource = resource;
this.inflater = ((MainActivity)ctx).getLayoutInflater();
}
#Override
public View getView(int pos, View convertView, ViewGroup parent) {
// (Re)Use convertView
if (convertView == null) {
convertView = inflater.inflate(itemResource, parent, false);
}
CheckedTextView checkView = (CheckedTextView) convertView;
checkView.setText(items.get(pos));
if (mCheckedItems.get(pos))
checkView.setChecked(true);
else
checkView.setChecked(false);
return convertView;
}
}
public class ActionBarCallBack implements ListView.OnItemClickListener,
ActionMode.Callback {
ActionMode actionMode;
AdapterView.OnItemClickListener previousListener;
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
Log.v(TAG, "Action mode started");
actionMode = mode;
mode.getMenuInflater().inflate(R.menu.cab_menu, menu);
previousListener = mListView.getOnItemClickListener();
mListView.setOnItemClickListener(this);
mCheckedItems = new SparseBooleanArray(mListView.getCount());
return true;
}
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.delete:
Log.v(TAG, "Deleting "+mCheckedItems.size()+" items");
for (int i= mCheckedItems.size()-1; i>=0; i--) {
int key = mCheckedItems.keyAt(i);
Log.v(TAG, "Removing array item # " + key);
mListArray.remove(key);
}
mode.finish();
return true;
default:
return false;
}
}
#Override
public void onDestroyActionMode(ActionMode mode) {
Log.v(TAG, "Exiting action mode.");
mListView.setOnItemClickListener(previousListener);
mCheckedItems.clear();
mAdapter.notifyDataSetChanged();
}
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
CheckedTextView checkView = (CheckedTextView) view;
boolean state = checkView.isChecked();
checkView.setChecked(!state);
if (!mCheckedItems.get(position))
mCheckedItems.put(position, true);
else
mCheckedItems.delete(position);
actionMode.setTitle(mCheckedItems.size() + " Items selected");
Log.v(TAG, "Action item # " + position +
" clicked. It's state now is " + state);
}
}
}
And here are my xml files create the whole look:
res/layout/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: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">
<ListView
android:id="#+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:drawSelectorOnTop="true"/>
<!-- Note that drawSelectorOnTop is important as it lets
the CheckedTextViews to be clicked in a normal way too-->
</RelativeLayout>
res/layout/list_item.xml:
<CheckedTextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:background="#drawable/list_selector"/>
res/drawable/list_selector.xml:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#color/item_default" android:state_checked="false"/>
<item android:drawable="#color/item_checked" android:state_checked="true"/>
</selector>
res/values/colors.xml:
<resources>
<color name="item_default">#33B5E5</color>
<color name="item_checked">#0095CC</color>
</resources>

Categories

Resources