I want to start a new activity from list view items from a fragment. But this isn't working. Here's the code:
public class SettingsF extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View root = (ViewGroup) inflater.inflate(R.layout.fragment_settings, container, false);
String[] menuitems = {"Context Setup", "Set-Up Custom Texts"};
ListView listView = (ListView) root.findViewById(R.id.listview_settings);
ArrayAdapter<String> listViewAdapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, menuitems);
listView.setAdapter(listViewAdapter);
listView.setOnClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (position == 1){
Intent intent;
intent = new Intent(getActivity(), contactselect.class);
startActivity(intent);
}
}
});
return root;
}
If you want to use event listener on ListView then you can use listview.setOnItemClickListener(new AdapetView). This (setOnClickListener) listener can't work on listview.
Listview contain multiple data.
Try this if you want to open an activity on item clicked:
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// your code
}
});
I have a ListView with several items and every item has it own Activity class to show details. How can I switch to an appropriate activity when user selects and item in this ListView?
My current code is following:
ListView listView;
ArrayAdapter<String> adapter;
String[] hotel = {"one room", "double room", "suit", "vip"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, hotel);
listView.setAdapter(adapter);
}
Add setOnItemClickListener to your listView in onCreate under listView.setAdapter(adapter); :
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
if(position == 0){
Intent intent = new Intent(MainActivity.this, OneRoomActivity.class);
startActivity(intent);
}
else if(position == 1){
Intent intent = new Intent(MainActivity.this, DoubleRoomActivity.class);
startActivity(intent);
}
//Do as above for rest of the list items
}
});
Hope this helps.
My MainActivity, which extends ActionBarActivity, has a ListView, which I want to reload using notifyDataSetChanged(), but I do not know how to do this.
My code so far:
public class MainActivity extends ActionBarActivity {
private JournalEntryDataSource datasource;
private ListView listView = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
datasource = new JournalEntryDataSource(this);
datasource.open();
listView = (ListView) findViewById(R.id.list);
List<JournalEntry> values = datasource.getAllJournalEntries();
listView.setAdapter(new ArrayAdapter<JournalEntry>(this, R.layout.list_item, R.id.lugares, values));
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
Log.i("app", "Deleting item number " + position);
datasource.deleteJournalEntry((JournalEntry) listView.getAdapter().getItem(position));
//I would like to do this here:
//ArrayAdapter<JournalEntry> adapter = (ArrayAdapter<JournalEntry>) getListAdapter();
//adapter.notifyDataSetChanged();
}
});
}
But I get an error when calling adapter.notifyDatasetChanged()...
Any tips? I've been looking at similar questions and no luck so far...
--------EDITED CODE---------
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
datasource = new JournalEntryDataSource(this);
datasource.open();
listView = (ListView) findViewById(R.id.list);
values = datasource.getAllJournalEntries();
listView.setAdapter(new ArrayAdapter<JournalEntry>(this, R.layout.list_item, R.id.lugares, values));
ArrayAdapter<JournalEntry> adapter = (ArrayAdapter<JournalEntry>) getListAdapter();
// use the SimpleCursorAdapter to show the
// elements in a ListView
listView.setAdapter(new ArrayAdapter<JournalEntry>(this, R.layout.list_item, R.id.lugares, values));
listView.setLongClickable(true);
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> parent, View v, int position, long id) {
Log.i("hola","borrando la posiciĆ³n "+position);
JournalEntry removeMe = (JournalEntry)listView.getAdapter().getItem(position);
values.remove(removeMe);
datasource.deleteJournalEntry(removeMe);
//adapter.notifyDataSetChanged();
reloadMe();
return true;
}
});
}
public void reloadMe(){
//need to do this better... but meh.
Intent intent = new Intent(this, MainActivity.class);
this.startActivity(intent);
}
protected ListView getListView() {
if (listView == null) {
listView = (ListView) findViewById(android.R.id.list);
}
return listView;
}
protected void setListAdapter(ListAdapter adapter) {
getListView().setAdapter(adapter);
}
protected ListAdapter getListAdapter() {
ListAdapter adapter = getListView().getAdapter();
if (adapter instanceof HeaderViewListAdapter) {
return ((HeaderViewListAdapter)adapter).getWrappedAdapter();
} else {
return adapter;
}
}
}
Updated Answer for updated code
instead of creating the same activity again, you should choose to set another new adapter object with the new values object.
public void reloadMe(){
//need to do this better... but meh.
//Intent intent = new Intent(this, MainActivity.class);
//this.startActivity(intent);
listView.setAdapter(new ArrayAdapter<JournalEntry>(this, R.layout.list_item, R.id.lugares, values));
}
Perhaps, you are deleting from
datasource.deleteJournalEntry((JournalEntry) listView.getAdapter().getItem(position));
But you did not set "datasource" as the data source of the adapter. If you look carefully you did set the "values" list object-
listView.setAdapter(new ArrayAdapter<JournalEntry>(this, R.layout.list_item, R.id.lugares, values));
Perhaps you may need to also remove from the values list also.
So I have two fragments linking to layout files which display ListViews. The ListViews are defined in the xml and have entries from a string array. I want to click on items in the ListView and open new activities. There are 8 items in one ListView and 9 in the other. In the onItemClick code, how do I create intents to start activities based on the item clicked? I will create 1 class per item as its own activity. How can I start the activities in the classes via intents inside the onItemClick methods of this code?
class CommunityFragment extends Fragment{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View view = inflater.inflate(R.layout.community_fragment, container, false);
ListView lv = (ListView) view.findViewById(R.id.communityListView);
lv.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3){
// TODO Auto-generated method stub
}
});
return view;
}
}
class ResourcesFragment extends Fragment{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View view = inflater.inflate(R.layout.resources_fragment, container, false);
ListView lv = (ListView) view.findViewById(R.id.resourcesListView);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
}
});
return view;
}
}
Implement your OnItemClickListener() like below
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
// TODO Auto-generated method stub
Intent intent = new Intent(getActivity(), nextactivity.class);
startActivity(intent);
}
});
Make switch statement for each items click and open activities accordingly as below:
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
int itm=arg0.getItemAtPosition(arg2);
switch (itm) {
case 0:
Toast.makeText(m_context, "Position Zero", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getActivity(), FirstActivity.class);
startActivity(intent);
break;
case 1:
Intent intent1 = new Intent(getActivity(), SecondActivity.class);
startActivity(intent1);
break;
case 2:
//..............................
}
});
on Item Click you will get Position based on position you can start fragment
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getApplicationContext(),
"Click ListItem Number " + position, Toast.LENGTH_LONG)
.show();
switch(position) {
case CONST_FRAGMENT_1 :
//Start fragment 1
...
...
}
}
});
one Generic solution can be ..
Create an array of items that hold class name of activity you want to open ..
like ..
Class[] activityArray = new Class[numberOfItemsInListView];
activityArray[0] = Activity1.class;
//add all activities like that..............
now on ListView onItemCLick :
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view,
int position, long arg3) {
Intent intent = new Intent(CommunityFragment.this.getActivity(), activityArray[postion]);
CommunityFragment.this.getActivity.startActivity(intent);
}
});
Use this to start next intent in your onItemClickListener:
Intent intent = new Intent(getActivity(), nextactivity.class);
startActivity(intent);
I think following code help you.
public class PdfListViewFragment extends Fragment {
ListView listView;
Activity rootView;
Activity context;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
//returning our layout file
//change R.layout.yourlayoutfilename for each of your fragments
View rootView = inflater.inflate(R.layout.pdf_list_view, container, false);
context = getActivity();
// Get ListView object from xml
listView = (ListView) rootView.findViewById(R.id.list);
// Defined Array values to show in ListView
String[] values = new String[]{"Android List View",
"Adapter implementation",
"Simple List View In Android",
"Create List View Android",
"Android Example",
"List View Source Code",
"List View Array Adapter",
"Android Example List View"
};
// Define a new Adapter
// First parameter - Context
// Second parameter - Layout for the row
// Third parameter - ID of the TextView to which the data is written
// Forth - the Array of data
ArrayAdapter<String> adapter = new ArrayAdapter<String>(context,
android.R.layout.simple_list_item_1, android.R.id.text1, values);
// Assign adapter to ListView
listView.setAdapter(adapter);
// ListView Item Click Listener
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if (position == 0) {
Intent myIntent = new Intent(view.getContext(), ListItemActivity1.class);
startActivityForResult(myIntent, 0);
}
if (position == 1) {
Intent myIntent = new Intent(view.getContext(), ListItemActivity2.class);
startActivityForResult(myIntent, 0);
}
if (position == 2) {
Intent myIntent = new Intent(view.getContext(), ListItemActivity1.class);
startActivityForResult(myIntent, 0);
}
if (position == 3) {
Intent myIntent = new Intent(view.getContext(), ListItemActivity2.class);
startActivityForResult(myIntent, 0);
}
if (position == 4) {
Intent myIntent = new Intent(view.getContext(), ListItemActivity1.class);
startActivityForResult(myIntent, 0);
}
if (position == 5) {
Intent myIntent = new Intent(view.getContext(), ListItemActivity2.class);
startActivityForResult(myIntent, 0);
}
if (position == 6) {
Intent myIntent = new Intent(view.getContext(), ListItemActivity1.class);
startActivityForResult(myIntent, 0);
}
if (position == 7) {
Intent myIntent = new Intent(view.getContext(), ListItemActivity2.class);
startActivityForResult(myIntent, 0);
}
// ListView Clicked item index
int itemPosition = position;
// ListView Clicked item value
String itemValue = (String) listView.getItemAtPosition(position);
// Show Alert
Toast.makeText(context.getApplicationContext(), "Position :" + itemPosition + " ListItem : " + itemValue, Toast.LENGTH_LONG).show();
}
});
return rootView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//you can set the title for your toolbar here for different fragments different titles
getActivity().setTitle("XYZ");
}
}
If you use an adapter to display the items in a list, it is important to differentiate the following:
The ID of the list AdapterView#getId() is different than the ID of the items in the list ArrayAdapter<String>#getId(), because the view of the list contains the views of the elements.
Suppose an example where you are going to launch activities with user roles. You will have to do the transformation for your particular case.
public class SignInFragment extends Fragment implements AdapterView.OnItemClickListener {
//TODO: Declare constants (GUEST, HOST, EMPLOYEE...)
private ArrayAdapter<String> userRolesAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_sign_in, container, false);
// ListView Instance
ListView userRolesList = root.findViewById(R.id.user_roles_list);
String[] userRoles = {
GUEST,
HOST,
EMPLOYEE
};
// Initialize the adapter
userRolesAdapter = new ArrayAdapter<>(
getActivity(),
android.R.layout.simple_list_item_1,
userRoles
);
// Link to the list with the adapter. This reference starts the process of filling the list.
userRolesList.setAdapter(userRolesAdapter);
// Events
userRolesList.setOnItemClickListener(this);
return root;
}
/**
* #param adapterView: View using the adapter from the list
* #param view: View of the item that has been pressed
* #param i: Refers to the position of the item that the adapter handles
*/
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
if (adapterView.getId() == R.id.user_roles_list) {
// Obtain the item pressed on the adapter with the entry position
String currentUserRol = userRolesAdapter.getItem(i);
assert currentUserRol != null;
switch (currentUserRol) {
case GUEST:
startActivity(Host.class);
break;
case HOST:
startActivity(Host.class);
break;
case EMPLOYEE:
startActivity(Employee.class);
break;
default:
Log.d("Error", "The activity passed as an argument to startActivity() does not exist");
break;
}
}
}
/**
* PRECONDITION: The class given as an argument exists.
*/
public void startActivity(Class<?> cls) {
Intent intent = new Intent(getActivity(), cls);
startActivity(intent);
}
}
Best :)
I have added leadbolt ad(entry ad). The advertising works correctly but listview.click doesn't work when I close ad from close sign. (Listview.click does not do anything, It works when I remove AdController)
public class SoundList extends ListActivity {
int [] soundfile;
MediaPlayer mediaPlayer;
private AdController myController;
final Activity act = this;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myController = new AdController(act, "111111111");
myController.loadAd();
soundfile= new int[] {R.raw.sound1,R.raw.sound2.....};
String[] sounds= getResources().getStringArray(R.array.sounds);
// Binding Array to ListAdapter
this.setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, R.id.label, sounds));
ListView lv = getListView();
lv.setDescendantFocusability(ListView.FOCUS_BLOCK_DESCENDANTS);
// listening to single list item on click
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent intent = new Intent(getApplicationContext(), SingleListItem.class);
intent.putExtra("position", position);
startActivity(intent);
}
});
}
Having a focusable item in a row of a ListView causes the OnItemClickListener NOT to be invoked.
To fix this issue add following code to row view.
XML:
android:descendantFocusability="blocksDescendants"
Java:
listItem.setDescendantFocusability(FOCUS_BLOCK_DESCENDANTS);