This is my first app and my first time posting so bear with me.
I'm trying to make it so the user can choose the background color of the entire app from a Change Skins screen. However with what I have now it only changes the color of the activity until it goes back to the main activity.
Here is the code for the Change Skins screen
package cs.pacificu.mypace;
import android.R.layout;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Layout;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class Skin extends Activity
{
#Override
public void onCreate(Bundle savedInstanceState)
{
final String[] SKINS = new String[] {"Light", "Dark"};
super.onCreate(savedInstanceState);
setContentView(R.layout.playlist);
final ListView listView = (ListView) findViewById (R.id.playlists);
listView.setAdapter(new ArrayAdapter<String> (this,R.layout.single_list_item,SKINS));
listView.setTextFilterEnabled(true);
listView.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id)
{
// When clicked, show a toast with the TextView text
Toast.makeText(getApplicationContext(),
((TextView) view).getText(), Toast.LENGTH_SHORT).show();
//
View layout = findViewById(R.layout.activity_main);
String selectedFromList = (listView.getItemAtPosition(position).toString ());
if (SKINS [0] == selectedFromList)
{
listView.setBackgroundColor(Color.CYAN);
//layout.setBackgroundColor(android.R.color.darker_gray);
}
else if (SKINS[1] == selectedFromList)
{
listView.setBackgroundColor(Color.BLACK);
//layout.setBackgroundColor(android.R.color.black);
}
//
finish();
}
});
}
}
And here is the main activity code
package cs.pacificu.mypace;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuItem;
/*import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.MenuInflater;*/
import android.view.View;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
startPlaylists(null);
}
#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)
{
switch (item.getItemId()) {
case R.id.skin:
changeSkin();
return true;
case R.id.action_settings:
settingsList();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void startPlaylists (View view)
{
Intent intentPlaylists = new Intent();
intentPlaylists.setClassName("cs.pacificu.mypace", "cs.pacificu.mypace.Playlist");
intentPlaylists.setAction("#strings/action_playlists");
startActivity(intentPlaylists);
}
public void changeSkin ()
{
Intent intentSkin = new Intent();
intentSkin.setClassName("cs.pacificu.mypace", "cs.pacificu.mypace.Skin");
intentSkin.setAction("#strings/action_skin");
startActivity(intentSkin);
}
public void settingsList ()
{
Intent intentSettings = new Intent();
intentSettings.setClassName("cs.pacificu.mypace", "cs.pacificu.mypace.Settings");
intentSettings.setAction("#strings/action_settings");
startActivity(intentSettings);
}
}
Thank you!
Put this on your xml
android:background="#025cd8"
Depending on your choice of color.
what you can do is set a SharedPreferences value to what the user selects, and at the start of each of your activities, set that value to the background colour of your layout. That is the best way I see to solving this.
So in all of your activities, you would set them to the value from the SharedPreferences and if not set use your default one. As for storing the possible values, you can either use the XML file or just hard code the values in one global class, although the former is preferable.
Look here and see what they did (Android-page-about-data-storage)
Edit:
If you are going to keep it simple like that, just background colour, then you can do something like this:
|- Keep these somewhat global, maybe in a class and access them as needed,
// Make sure to maintain the connection
String[] SKINS = {"Light", "Dark"};
int[] COLOURS = {Color.CYAN, Color.BLACK};
|- For the onItemClick(),
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id)
{
// You may wish to make these two variables class-global
SharedPreferences settings = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("mskin", COLOURS[position]);
editor.commit();
// For on the spot changes
listView.setBackgroundColor(COLOURS[position]);
// Your other code, as you wish, before or after, depends on how you need it.
|- As for your other activities, or at the onCreate() of all activities,
SharedPreferences settings = getPreferences(MODE_PRIVATE);
listView.setBackgroundColor(settings.getInt("mskin", COLOURS[0]));
Related
I'm trying to set up an action bar for my app in Android studio.
I've been following the Google tutorial, however for some reason, the items I put on the bar do not appear when running the app. They do however appear in the design window.
Image of the design window
Image of the app
This is the XML, as copied from the Google tutorial
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<!-- "Mark Favorite", should appear as action button if possible -->
<item
android:id="#+id/action_favorite"
android:icon="#drawable/ic_favorite_black_48dp"
android:title="#string/action_favorite"
app:showAsAction="ifRoom"/>
<!-- Settings, should always be in the overflow -->
<item
android:id="#+id/action_settings"
android:title="#string/action_settings"
app:showAsAction="never"/>
</menu>
here's the complete code of the main activity, at the bottom of which I attempt to use the action bar items.
package php.comget_all.ipeelu.httpweb_service_test.intenseapp;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Stack;
public class MainActivity extends AppCompatActivity {
private Button sendButton;
public EditText editText;
public Stack<TableRow> messageStack;
public LinearLayout messagesDisplayLayout;
public ScrollView scroller;
private TextView response;
private EditText editTextAddress, editTextPort;
private Button buttonConnect, buttonClear;
private Client client;
// Boolean telling us whether a download is in progress, so we don't trigger overlapping
// downloads with consecutive button clicks.
private boolean mDownloading = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(myToolbar);
client = new Client("10.0.2.2", 12345, this);
client.execute();
messagesDisplayLayout = (TableLayout) findViewById(R.id.messageDisplay);
sendButton = (Button) findViewById(R.id.sendButton);
editText = (EditText) findViewById(R.id.edit_message);
scroller = (ScrollView) findViewById(R.id.scroller);
editText.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(s.length() != 0)
sendButton.setEnabled(true);
else
sendButton.setEnabled(false);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
#Override
public void afterTextChanged(Editable s) {}
});
messageStack = new Stack<TableRow>();
}
/** Called when the user clicks the Send button */
public void sendMessage(View view)
{
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("hh:mm");
String ts = simpleDateFormat.format(new Date());
String message = editText.getText().toString();
TextView messageTV = new TextView(this);
messageTV.setText(ts + ": " + message);
messageTV.setTextSize(20);
TableRow messageRow = new TableRow(this);
messageRow.setPadding(0,20,0,0);
messageRow.addView(messageTV);
messageTV.getLayoutParams().width = LinearLayout.LayoutParams.WRAP_CONTENT;
messageTV.getLayoutParams().height = LinearLayout.LayoutParams.WRAP_CONTENT;
messagesDisplayLayout.addView(messageRow);
messageStack.push(messageRow);
editText.getText().clear();
scroller.fullScroll(scroller.FOCUS_DOWN);
//client.sendMessage(message);
synchronized (client.thingy)
{
client.message = message;
client.thingy.notify();
}
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
// User chose the "Settings" item, show the app settings UI...
return true;
case R.id.action_favorite:
// User chose the "Favorite" action, mark the current item
// as a favorite...
return true;
default:
// If we got here, the user's action was not recognized.
// Invoke the superclass to handle it.
return super.onOptionsItemSelected(item);
}
}
}
I'm sorry if I make any rookie mistakes, I'm as new to Android Studio as can be. However I've looked this up and really couldn't find a working answer anywhere, so this is my last resort.
you never inflate the menu, you need to override onCreateOptionsMenu
Example
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.my_menu, menu);
return true;
}
i am trying to make a note app.in an array i want to make id´s.
i want to check the id with an onclicklistener.
in the onclicklistener i make an Intent and an ExtraString
in this Extrastring i want to write the content from the note file i created
this is the code :
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.method.ScrollingMovementMethod;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import java.util.ArrayList;
import java.util.List;
public class NotizOeffnungsMenue extends Activity implements View.OnClickListener {
Button[] NoteListBtn ;
String[] NoteList ;
int [] e;
int i;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notiz_oeffnungs_menue);
LinearLayout l1 = (LinearLayout)findViewById(R.id.layout1);
NoteListBtn = new Button[fileList().length];
NoteList = fileList();
i = 0;
while (i < fileList().length)
{
NoteListBtn[i] = new Button(this);
NoteListBtn[i].setText(NoteList[i]);
NoteListBtn[i].setOnClickListener(this);
l1.addView(NoteListBtn[i]);
NoteListBtn[i].setId(i);
e [i] =i;
i++;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.notiz_oeffnungs_menue, 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onClick(View view)
{
if(e[] == view.getId())
{
Intent switchintent = new Intent(this,NotizActivity.class);
String EXTRA_INHALT;
startActivity(switchintent);
}
}
}
In onClick() I would recommend u to use switch case statement
switch(v.getId()){
case R.id.butnid:
//do something here
break;
case R.id.butnid2:
//do something here
break;
}
Make as many cases as u want.
And remember that the buttons u use should do this
butnid.setOnClickListener(this);
butnid2.setOnClickListener(this);
//And so on for ever id u use in on click
You can use like this:
#Override
public void onClick(View view)
{
Intent switchintent = new Intent(this,NotizActivity.class);
switchintent.putExtra("EXTRA_INHALT", e[view.getId()]);
switchintent.putExtra("EXTRA_INHALT2", NoteList[view.getId()]);
startActivity(switchintent);
}
Instead of comparing id, you can use that as a position. Because you are already setting that position as Id.
Hope this helps.
Im using intents to pass the noteId from my database to a different activity for displaying the information it was working and i went to work on another part of the project and now it seems to only pass one value and from playing about i have found that seems to be whatever is the next highest object on the ListView. Sorry if this is badly worded, Im not very good at explaining these things
ViewNote Class
package com.hardy.passnotes;
import java.util.HashMap;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class ViewNote extends Activity {
EditText NewNoteTitle;
EditText NewNoteContent;
TextView tvNoteId;
DBTools dbTools = new DBTools(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_note);
NewNoteTitle = (EditText)findViewById(R.id.ETNewNoteTitle);
NewNoteContent = (EditText)findViewById(R.id.ETNewNoteContent);
Intent n = getIntent();
String NoteId = n.getStringExtra("noteId");
Toast.makeText(getApplicationContext(), NoteId,
Toast.LENGTH_LONG).show();
HashMap<String, String> NoteList = dbTools.getNoteInfo(NoteId);
if(NoteList.size() != 0)
{
setTitle("Note: " + NoteList.get("noteTitle"));
NewNoteTitle.setText(NoteList.get("noteTitle"));
NewNoteContent.setText(NoteList.get("noteContent"));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.view_note, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId())
{
case R.id.action_Editnote:
tvNoteId = (TextView)findViewById(R.id.NoteId);
String NoteValue = tvNoteId.getText().toString();
Intent intent = new Intent(getApplication(),EditNote.class);
intent.putExtra("noteId", NoteValue);
startActivity(intent);
case R.id.action_DelNote:
Intent intent1 = getIntent();
String NoteId = intent1.getStringExtra("noteId");
dbTools.deleteNote(NoteId);
Intent i = new Intent(getApplication(),MyNotes.class);
startActivity(i);
finish();
}
return super.onOptionsItemSelected(item);
}
}
MyNote Class:
package com.hardy.passnotes;
import java.util.ArrayList;
import java.util.HashMap;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class MyNotes extends ListActivity {
DBTools dbTools = new DBTools(this);
TextView tvNoteId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_notes);
Log.i("Tag", "OnCreate Started As Normal");
setTitle("My Notes");
ArrayList <HashMap<String, String>> NoteList = dbTools.getAllNotes();
if(NoteList.size() != 0)
{
ListView listView = getListView();
listView.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View view,
int position, long id) {
tvNoteId = (TextView)findViewById(R.id.NoteId);
String NoteValue = tvNoteId.getText().toString();
Intent intent = new Intent(MyNotes.this,ViewNote.class);
intent.putExtra("noteId", NoteValue);
startActivity(intent);
Log.i("Tag", "if Started As Normal");
}
});
ListAdapter Adapter = new SimpleAdapter(MyNotes.this,NoteList,R.layout.notes_list, new String[]{"noteId","noteTitle",}, new int[]{R.id.NoteId,R.id.NoteTitle} );
setListAdapter(Adapter);
Log.i("Tag", "Arrey Started As Normal");
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.my_notes, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId())
{
case R.id.action_Add:
Intent i = new Intent(getApplicationContext(),CreateNote.class);
startActivity(i);
finish();
}
return super.onOptionsItemSelected(item);
}
}
Thanks in advance been searching around and debugging for hours with no luck.
Hi I think the problem is that you use the findViewById() method inappropriately in your onItemClick listener.
You should use:
tvNoteId = (TextView)view.findViewById(R.id.NoteId);
Notice that I call the findViewById method on the view given by the onItemClick method because you want to find the view with the id NoteId from the pressed item and not from the entire's activity content view.. the way you do it will search in the content view of your activity for the first id equal with NoteId ...
I think your note get deleted on the moment edit is clicked from the options menu.
At the end of case R.id.action_Editnote nothing is returned nor break is called so case R.id.action_Delnote will be executed as well. This is where you delete the note from your database.
In your switch, put a break:
switch (item.getItemId())
{
case R.id.action_Editnote:
tvNoteId = (TextView)findViewById(R.id.NoteId);
String NoteValue = tvNoteId.getText().toString();
Intent intent = new Intent(getApplication(),EditNote.class);
intent.putExtra("noteId", NoteValue);
startActivity(intent);
break;
case R.id.action_DelNote:
Intent intent1 = getIntent();
String NoteId = intent1.getStringExtra("noteId");
dbTools.deleteNote(NoteId);
Intent i = new Intent(getApplication(),MyNotes.class);
startActivity(i);
finish();
break;
}
So I have a weird problem. I have 2 Activities I'm working on. One of the Activities displays a ListView whose data is grabbed via a long Extra I use to fetch the results via a WHERE clause in the database.query. The other Activity is called when a ListView item is clicked, allowing someone to add something to the database for the ListView.
The activity names are DaysActivity.java (the activity with the listview) and DayAddActivity.java (the Activity that allows someone to add a day, which then shows up in the DaysActivity.java ListView).
The problem I'm having is, when I finish() DayAddActivity.java it goes back to DaysActivity and the ListView is still there fully populated. However, if I hit the back button in DayAddActivity.java (the button to the left of the title in the action bar with my app icon), when it goes back to DaysActivity.java, the ListView is empty/gone.
Heres the code for both:
DaysActivity.java:
package com.gauvion.gfit;
import android.annotation.SuppressLint;
import android.app.ListActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
public class DaysActivity extends ListActivity {
private DaysDataSource datasource;
private SimpleCursorAdapter dataAdapter;
private boolean isEditing = false;
private Toast toast_deleted;
private String[] columns = new String[] { MySQLiteHelper.COLUMN_NAME, MySQLiteHelper.COLUMN_DAY };
private int[] to;
private long routineDataID;
private String routineDataName;
#SuppressLint("ShowToast")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_days);
routineDataID = getIntent().getLongExtra("routineDataID", 0);
routineDataName = getIntent().getStringExtra("routineDataName");
setTitle(routineDataName);
toast_deleted = Toast.makeText(this, "", Toast.LENGTH_SHORT);
datasource = new DaysDataSource(this);
datasource.open();
Cursor cursor = datasource.fetchAllDays(routineDataID);
to = new int[] { R.id.listitem_day_name, R.id.listitem_day_day };
dataAdapter = new SimpleCursorAdapter(this, R.layout.listitem_day, cursor, columns, to, 0);
setListAdapter(dataAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_days, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Cursor cursor = datasource.fetchAllDays(routineDataID);
switch (item.getItemId()) {
case R.id.button_days_add:
Intent startDayAdd = new Intent(this, DayAddActivity.class);
startDayAdd.putExtra("routineDataID", routineDataID);
this.startActivity(startDayAdd);
return true;
case R.id.button_days_edit:
to = new int[] { R.id.listitem_day_edit_name, R.id.listitem_day_edit_day };
dataAdapter = new SimpleCursorAdapter(this, R.layout.listitem_day_edit, cursor, columns, to, 0);
setListAdapter(dataAdapter);
isEditing = true;
invalidateOptionsMenu();
return true;
case R.id.button_days_edit_done:
to = new int[] { R.id.listitem_day_name, R.id.listitem_day_day };
dataAdapter = new SimpleCursorAdapter(this, R.layout.listitem_day, cursor, columns, to, 0);
setListAdapter(dataAdapter);
isEditing = false;
invalidateOptionsMenu();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
menu.findItem(R.id.button_days_edit).setVisible(!isEditing);
menu.findItem(R.id.button_days_edit_done).setVisible(isEditing);
return true;
}
#Override
protected void onResume() {
datasource.open();
Cursor cursor = datasource.fetchAllDays(routineDataID);
dataAdapter.changeCursor(cursor);
super.onResume();
}
#Override
protected void onPause() {
datasource.close();
super.onPause();
}
}
DayAddActivity.java:
package com.gauvion.gfit;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import android.support.v4.app.NavUtils;
public class DayAddActivity extends Activity {
private RoutinesDataSource datasource;
private EditText dayName;
private Spinner dayDay;
private Button saveButton;
private long routineDataID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_day_add);
routineDataID = getIntent().getLongExtra("routineDataID", 0);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_day_add, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
public void cancelDay(View view) {
this.finish();
}
}
The cancelDay() function is called when a "Cancel" button is clicked in activity_day_add.xml. Like I said, when I click the "Cancel" button inside of DayAddActivity.java, it goes back to DaysActivity.java and the ListView is fine. All data is there. However, if I press the back button in the action bar (the button containing a back arrow and my app icon beside the title of the Activity) the ListView for DaysActivity.java is empty/gone, and the title is also empty (because this is also generated through an Extra String value).
Your cursors are not managed by the activity, this can cause a memory leak or even ANR. You should consider using a loader to populate a list using a cursor. You can find an example here :http://developer.android.com/guide/components/loaders.html.
Loaders work better as they don't freeze the app when the connexion to the database is obtained and they will be passed from one instance of your activity to another, preventing memory leaks and reusing resources.
But again, as in your previous post : Extras seem to be lost onResume(), you should understand the link between onSaveInstanceState and onCreate to pass arguments to the future self of your activity. Look at this post, the answer with the biggest score : onSaveInstanceState () and onRestoreInstanceState ().
It seems like your Context has some problems in "this.startActivity(startDayAdd);" line. try using "DaysActivity.this.startActivity(startDayAdd);". if it doesnot work then use breakpoints to see line by line execution.
hey all.. i have been looking at other questions to get help and answers without luck..
my problem is that i want to open different class from my listView. according to the specific name in the listView. . the names are in lv_arr[] ..
If anybody can give a detailed answer i will be very thankfull and happy..
Im new in android and not the best in java :-(
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class StatusActivity extends Activity implements OnItemClickListener {
public ListView lv1;
public String lv_arr[]= {"John", "Andrew","alex","alice","bob","bla bla"};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tabview);
lv1=(ListView)findViewById(R.id.ListView01);
lv1.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , lv_arr));
lv1.setOnItemClickListener(this);
}
public boolean onCreateOptionsMenu(Menu menu) {
new MenuInflater(getApplication())
.inflate(R.menu.menu, menu);
return(super.onPrepareOptionsMenu(menu));
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.close:
super.finish();
break;
case R.id.icontext:
Intent i = new Intent(this, InfoActivity.class);
startActivity(i);
break;
}
return true;
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
if(position == 0){
//Intent w = new Intent (this, Seekbar.class);
//startActivity(w);
Toast.makeText(this, "You pressed the first item in the list", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(this, "You pressed all other items in the list", Toast.LENGTH_SHORT).show();
}
}
}
try this....if you have doubts add comment.
edited:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tabview);
lv1=(ListView)findViewById(R.id.ListView01);
lv1.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , lv_arr));
lv1.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
if(position==0){
Intent i = new Intent(this, InfoActivity.class);
startActivity(i);
} else if(position==1){
start another activity here...
}
}
});
}
hope it helps..
well i think you want to know basically the flow of how it is possible.
If all the classes which should be opened are more likely the same with just text and image changes and same layout then you dont need to create separate class file for each and every item clicked.
Just create one class file and one xml file and on item click pass on the bundle to the class file which will just changes the content on different item clicks and will workk as a charm as with this flow you will have only one class file and one xml file for all the list items you have
If you dont want to keep the same layout then you can obviously make the some views gone, visible or invisible at runtime
try something like this
public String lv_class_names[]= {Activity1.class.getName(), Activity2.class.getName(), Activity3.class.getName(), .....};
In the onItemClick method write
Intent i = new Intent(this, Class.forName(lv_class_name[position]));
startActivity(i);
for more details see this