sorry I'm fairly new to android so I seem to keep getting stuck on the simplest things.
I had two projects I had completed for a class. One was a simple To Do List and another that allowed different fragments to be used depending on whether you are in portrait or landscape mode. both worked but when trying to combine the two I get an error when put my To Do activity in the fragment if I extend Fragment (findByViews and setContentView dont work.
I can replace Fragment with FragmentActivity which fixes this but then my MainActivity.java's fragmentTransaction.replace(android.R.id.content, pm_fragment); gets an error saying:
"replace (int, android.app.Fragment) in FragmentTransaction cannot be applied to (int, com.android.MyFragmentsTodo.PM_Fragment)"
Can anyone tell me what I can do to make this work? I have a test tomorrow and I'm worried the lecturer might want us to mix an activity with fragments.
Any help would be greatly appreciated.
MainActivity.java
package com.android.myfragmentstodo;
import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.res.Configuration;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends ActionBarActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Configuration config = getResources().getConfiguration();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
//check device orientation and act upon it
if(config.orientation == Configuration.ORIENTATION_LANDSCAPE){
// If orientation is landscape then
LM_Fragment ls_fragment = new LM_Fragment();
fragmentTransaction.replace(android.R.id.content, ls_fragment);
}else{
// If orientation is portrait then
PM_Fragment pm_fragment = new PM_Fragment();
fragmentTransaction.replace(android.R.id.content, pm_fragment);
}
//apply (commit) the changes
fragmentTransaction.commit();
}
#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);
}
}
PM_Fragment.java
package com.android.myfragmentstodo;
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.ActionBarActivity;
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.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
/**
* Created by Malan on 4/20/2015.
*/
public class PM_Fragment extends android.support.v4.app.Fragment {
private ArrayList<String> items;
private ArrayAdapter<String> adapter;
private ListView listView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedinstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.todoItems);
items = new ArrayList<String>();
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items);
listView.setAdapter(adapter);
Button button = (Button) findViewById(R.id.btnAddItem);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText editText = (EditText) findViewById(R.id.todoEdit);
String itemText = editText.getText().toString();
adapter.add(itemText);
editText.setText("");
Toast toast = Toast.makeText(getApplicationContext(), "Item Added", Toast.LENGTH_SHORT);
toast.show();
}
});
setupListViewListener();
return inflater.inflate(R.layout.lm_fragment, container, false);
}
private void setupListViewListener() {
listView.setOnItemLongClickListener(
new AdapterView.OnItemLongClickListener(){
#Override
public boolean onItemLongClick(AdapterView<?> av,
View item, int pos, long id){
items.remove(pos);
adapter.notifyDataSetChanged();
return true;
}
});
}
#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);
}
public void AddItem(View view) {
EditText editText = (EditText) findViewById(R.id.todoEdit);
String itemText = editText.getText().toString();
adapter.add(itemText);
editText.setText("");
}
}
OK i have figured out how to fix the issue. One must keep extending Fragment but when doing using findViewById one must use:
rootView = inflater.inflate(R.layout.pm_fragment, container, false);
and then precede all findViewById's with rootView like this:
listView = (ListView) rootView.findViewById(R.id.todoItems);
Whenever "this" is used instead use "getActivity()" for example:
adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, items);
when using getApplicationContext you must use getActivity().getApplicationContext() for example:
Toast toast = Toast.makeText(getActivity().getApplicationContext(), "Item Added", Toast.LENGTH_SHORT);
in the end my PM_Fragment is altered to look like this:
PM_Fragment.java
package com.android.myfragmentstodo;
import android.app.Fragment;
import android.os.Bundle;
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.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
/**
* Created by Malan on 4/20/2015.
*/
public class PM_Fragment extends Fragment {
private ArrayList<String> items;
private ArrayAdapter<String> adapter;
private ListView listView;
View rootView;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedinstanceState){
rootView = inflater.inflate(R.layout.pm_fragment, container, false);
listView = (ListView) rootView.findViewById(R.id.todoItems);
items = new ArrayList<String>();
adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, items);
listView.setAdapter(adapter);
Button button = (Button) rootView.findViewById(R.id.btnAddItem);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText editText = (EditText) rootView.findViewById(R.id.todoEdit);
String itemText = editText.getText().toString();
adapter.add(itemText);
editText.setText("");
Toast toast = Toast.makeText(getActivity().getApplicationContext(), "Item Added", Toast.LENGTH_SHORT);
toast.show();
}
});
setupListViewListener();
return rootView;
}
private void setupListViewListener() {
listView.setOnItemLongClickListener(
new AdapterView.OnItemLongClickListener(){
#Override
public boolean onItemLongClick(AdapterView<?> av,
View item, int pos, long id){
items.remove(pos);
adapter.notifyDataSetChanged();
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);
}
public void AddItem(View view) {
EditText editText = (EditText) rootView.findViewById(R.id.todoEdit);
String itemText = editText.getText().toString();
adapter.add(itemText);
editText.setText("");
}
}
Related
When I add a header to my listview it messes up my onclick,it selects the wrong item every time.
package ie.example.artur.projectrepeat;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
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.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class DataListActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
ListView listView;
SQLiteDatabase sqLiteDatabase;
DatabaseClass database;
Cursor cursor;
ListDataAdapter listDataAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.data_list_layout);
listView = (ListView) findViewById(R.id.list_view);
listDataAdapter = new ListDataAdapter(getApplicationContext(), R.layout.row_layout);
listView.setAdapter(listDataAdapter);
listView.setOnItemClickListener(this);
database = new DatabaseClass(getApplicationContext());
sqLiteDatabase = database.getReadableDatabase();
Cursor cursor=database.getInformation(sqLiteDatabase);
if (cursor.moveToFirst()) {
do {
String id, product_name, category,quantity,importance;
id = cursor.getString(0);
product_name = cursor.getString(1);
category = cursor.getString(2);
quantity = cursor.getString(3);
importance = cursor.getString(4);
DataProvider dataProvider = new DataProvider(id, product_name, category,quantity,importance);
listDataAdapter.add(dataProvider);
} while (cursor.moveToNext());
}
}
#Override
public void onItemClick(AdapterView<?> parent, final View view, final int position, long id) {
final TextView tv = (TextView) view.findViewById(R.id.product_id);
AlertDialog.Builder alert = new AlertDialog.Builder(
DataListActivity.this);
alert.setTitle("Alert!!");
alert.setMessage("Are you sure to delete record");
alert.setPositiveButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//do your work here
sqLiteDatabase = database.getReadableDatabase();
DatabaseClass.DeleteInformation(tv.getText().toString(), sqLiteDatabase);
listView.setAdapter(listDataAdapter);
listDataAdapter.notifyDataSetChanged();
listDataAdapter.removeItemAt(position);
dialog.dismiss();
}
});
alert.setNegativeButton("NO", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alert.show();
}
#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.
{
switch (item.getItemId())
{
case R.id.home : startActivity (new Intent(this, Main2Activity.class));
break;
case R.id.action_settings : startActivity (new Intent(this, SecondActivity.class));
break;
case R.id.catalogue :startActivity (new Intent(this, ViewAllItems.class));
break;
case R.id.ViewList :startActivity (new Intent(this, DataListActivity.class));
break;
case R.id.find :startActivity (new Intent(this, Main3Activity.class));
break;
case R.id.Update :startActivity (new Intent(this, Edit_Activity.class));
break;
}
return super.onOptionsItemSelected(item);
}}
}
When I add this code it messes up my app:
LayoutInflater myinflater = getLayoutInflater();
ViewGroup myHeader = (ViewGroup)myinflater.inflate(R.layout.header, listView, false);
listView.addHeaderView(myHeader, null, false)
The reason for that is that the header counts as additional one item inside your listview so when click on item you get the item in position - 1.
Add this inside onItemClick:
position -= listView.getHeaderViewsCount(); // or position - 1
I want to make my class and layout change when I click on specific items. For example, if I click "physical" from the array list I want it to open up the physical java class and the physical xml layout. How do i do this? As you can see down below I have already tried with the View view and switch/case.
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import android.support.v4.app.FragmentActivity;
import java.util.List;
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener{
private DrawerLayout drawerLayout;
private Toolbar toolbar;
private ListView listView;
private String[] planets;
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_appbar);
toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
NavigationDrawerFragment drawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
drawerFragment.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), toolbar);
drawerLayout=(DrawerLayout)findViewById(R.id.drawerLayout);
planets=getResources().getStringArray(R.array.planets);
listView=(ListView) findViewById(R.id.drawerList);
listView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, planets));
listView.setOnItemClickListener(this);
}
#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
return super.onOptionsItemSelected(item);
}
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(this, planets[position] + " was selected", Toast.LENGTH_LONG).show();
selectItem(position);
selectItem2(view);
}
public void selectItem(int position) {
listView.setItemChecked(position, true);
setTitle(planets[position]);}
public void selectItem2 (View view){
switch (view.getId()) {
case 0:
Intent intent = new Intent(view.getContext(), physical_fragment.class);
startActivityForResult(intent, 0);}}
public void setTitle(String title){
getSupportActionBar().setTitle(title);
}
}
You probably don't want compare the id of the View since all of the Views in your list will use android.R.layout.simple_list_item_1 they will all have the same id.
You may consider passing the position and comparing that.
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(this, planets[position] + " was selected", Toast.LENGTH_LONG).show();
selectItem(position);
selectItem2(position);
}
public void selectItem2 (int position) {
switch (position) {
case 0:
Intent intent = new Intent(MainActivity .this, physical_fragment.class);
startActivityForResult(intent, 0);
break;
}
}
Something like that should get you started. However, you may eventually want to check the content of the item selected such as the the actual position of the string resource then get that id in case you decide to switch around the list items or modify them in some other way.
I have no idea on what is wrong with my code.
My application is using navigation drawer. There are 4 different fragments and one of it is a cardview fragment which I have converted earlier from activity to fragment.
The cardview fragment is being underlined red which shows error that would not able to be compiled. Kindly refer the attached pictures.
If I were to accept the proposed solutions by the Android Studio,it will just solve the CardViewFragment and new problem would occur at the other 3 fragments.
And this is both my main activity and the cardview fragment.
MainActivity.java
package info.androidhive.materialdesign.activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import info.androidhive.materialdesign.R;
public class MainActivity extends AppCompatActivity implements FragmentDrawer.FragmentDrawerListener {
private static String TAG = MainActivity.class.getSimpleName();
private Toolbar mToolbar;
private FragmentDrawer drawerFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
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 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 FriendsFragment();
title = getString(R.string.title_friends);
break;
case 2:
fragment = new MessagesFragment();
title = getString(R.string.title_messages);
break;
case 3:
fragment = new CardViewFragment();
title = getString(R.string.title_messages);
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);
}
}
}
CardViewFragment.java
package info.androidhive.materialdesign.activity;
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.CardView;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import java.util.ArrayList;
import info.androidhive.materialdesign.R;
public class CardViewFragment extends Fragment {
private Toolbar toolbar;
private RecyclerView recyclerView;
private CardView cardView;
private ArrayList<FeddProperties> os_versions;
private RecyclerView.Adapter mAdapter;
// private RecyclerView.LayoutManager mLayoutManager;
private LinearLayout llLayout;
private FragmentActivity faActivity;
#Override
/*protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initContrls();
}*/
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
faActivity=(FragmentActivity)
super.getActivity();
llLayout=(LinearLayout)
inflater.inflate(R.layout.activity_main, container, false);
initContrls();
return llLayout;
}
private void initContrls() {
//toolbar = (Toolbar) findViewById(R.id.toolbar);
// cardView = (CardView) findViewById(R.id.cardList);
recyclerView = (RecyclerView) llLayout.findViewById(R.id.my_recycler_view);
/*if (toolbar != null) {
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Android Versions");
}*/
final String[] versions = {"Alpha", "Beta", "CupCake", "Donut",
"Eclair", "Froyo", "Gingerbread", "Honeycomb",
"Ice Cream Sandwitch", "JellyBean", "KitKat", "LollyPop"};
final int[] icons = {R.drawable.ic_launcher, R.drawable.ic_launcher, R.drawable.ic_launcher, R.drawable.donut, R.drawable.eclair, R.drawable.froyo, R.drawable.gingerbread, R.drawable.honeycomb, R.drawable.icecream_sandwhich, R.drawable.jellybean, R.drawable.kitkat, R.drawable.lollipop};
os_versions = new ArrayList<FeddProperties>();
for (int i = 0; i < versions.length; i++) {
FeddProperties feed = new FeddProperties();
feed.setTitle(versions[i]);
feed.setThumbnail(icons[i]);
os_versions.add(feed);
}
recyclerView.setHasFixedSize(true);
// ListView
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
//Grid View
// recyclerView.setLayoutManager(new GridLayoutManager(this,2,1,false));
//StaggeredGridView
// recyclerView.setLayoutManager(new StaggeredGridLayoutManager(2,1));
// create an Object for Adapter
mAdapter = new CardViewDataAdapter(os_versions);
// set the adapter object to the Recyclerview
recyclerView.setAdapter(mAdapter);
}
/* #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);
}*/
}
In MainActivity.java, you declared
import android.support.v4.app.Fragment
Import the same type of Fragment in CardViewFragment.java instead of
import android.app.Fragment;
so that it's clear that the same type of Fragment is being used in both pieces of code.
I'm new to android programming and i need some help. I created a list, here is the code, and i want to pass to a new activity by clicking on an item in the list, can anybody suggest me how to do it step by step? Thanks!
package com.example.andrian.testapp;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.app.Activity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.AdapterView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import com.example.andrian.testapp.R;
public class MainActivity extends ActionBarActivity {
ListView listView ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.list);
String[] values = new String[] {
"L0",
"L1",
"L2",
"L3",
"L4",
"L5",
"L6",
"L7"
};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, values);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
int itemPosition = position;
String itemValue = (String) listView.getItemAtPosition(position);
Toast.makeText(getApplicationContext(),
"Position: " + itemPosition + " List Item: " + itemValue, Toast.LENGTH_LONG)
.show();
}
});
}
#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) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Replace YOUR_ACTIVITY_NAME with the name of the new activity
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(getApplicationContext(),YOUR_ACTIVIY_NAME.class);
startActivity(intent);
}
});
Good luck.
I have a listview that uses a custom arrayadapter that loads a layout with text + a radiobutton. The user should only be able to select a single item in the list at a time - so basically only one radio button should be 'checked' at any time. This works perfectly except when the activity is recreated, like when the screen is rotated. I can't figure out why it's doing this, so maybe you all can think of something?
Here's the code for the activity that has the listview:
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.support.v4.app.NavUtils;
import android.widget.AdapterView;
public class TimeForm extends Activity implements AdapterView.OnItemClickListener {
private MyArrayAdapter maa;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_time_form);
// Show the Up button in the action bar.
getActionBar().setDisplayHomeAsUpEnabled(true);
ListView lv = (ListView) findViewById(R.id.listView1);
lv.setItemsCanFocus(false);
String listitems[] = new String[16];
listitems[0] = "Other";
for(int i = 1; i < 16; i++)
{
listitems[i] = "Job " + i;
}
maa = new MyArrayAdapter(this, R.layout.layout_list, listitems);
if(savedInstanceState != null)
maa.selIndex = savedInstanceState.getInt("selIndex");
lv.setAdapter(maa);
lv.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
EditText et = (EditText) this.findViewById(R.id.editText1);
if(position == 0)
{
et.setVisibility(View.VISIBLE);
} else {
et.setVisibility(View.GONE);
}
if(maa.selItem != null)
{
RadioButton rOld = (RadioButton) maa.selItem.findViewById(R.id.radioButton1);
rOld.setChecked(false);
}
RadioButton r = (RadioButton) view.findViewById(R.id.radioButton1);
r.setChecked(true);
maa.selIndex = position;
maa.selItem = view;
}
public void onSaveInstanceState(Bundle b)
{
b.putInt("selIndex", maa.selIndex);
super.onSaveInstanceState(b);
}
#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_time_form, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}
Code for MyArrayAdapter class:
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.RadioButton;
import android.widget.TextView;
public class MyArrayAdapter extends ArrayAdapter<String> {
private Context context;
private String[] strings;
private int layoutID;
public int selIndex;
public View selItem;
public MyArrayAdapter(Context c, int id, String[] values)
{
super(c, id, values);
selIndex = -1;
selItem = null;
this.strings = values;
this.context = c;
layoutID = id;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rView = inflater.inflate(layoutID, parent, false);
TextView tv = (TextView) rView.findViewById(R.id.textView1);
tv.setText(strings[position]);
if(position == selIndex)
{
RadioButton r = (RadioButton) rView.findViewById(R.id.radioButton1);
r.setChecked(true);
selItem = rView;
}
return rView;
}
}
Well, first thing's first, with regards to 're-creating' the view.. check out http://developer.android.com/guide/topics/resources/runtime-changes.html.
You can define public void onConfigurationChanged(Configuration newConfig) to ensure that your activity isn't recreated on rotation, for example.
That said, if you want to persist the values, you'll have to actually do that, and then apply any selections to your collection passed into your ArrayAdapter.
I figured it out. I'm not sure it's the best possible solution, but it works and doesn't cause any noticeable performance loss. ^_^
In the TimeForm activity's onItemClick() method, i added this at the bottom:
ListView lv = (ListView) findViewById(R.id.listView1);
lv.invalidateViews();
This forces the listview to redraw all the child views. Thanks to everyone who took the time to help me figure this out.