How to create a layout like Android CallLog's layout - android

Hey I want to create a layout like this for my application. Of course the functionalities will be differents. I'm studying the source code for this, and I found the xml files that does that. I just dont know how to implement that in the activity, how to call, what to create, a listview, etc.
I mean, I just want to list the name with a bigger font and the date like in the image, with a small font but aligned to the right.
Because, I want to get the data from the database I've created and print it like this list of CallLog.
I mean, how Android makes the date with that icon align in the right, with a small font size?
So this is my activity, I just dont know what xml file from the source code to use, or what method to implement so I can print the data like the image example.
public class RatedCalls extends ListActivity {
private static final String LOG_TAG = "RatedCalls";
private TableLayout table;
private CallDataHelper cdh;
private TableRow row;
private TableRow row2;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recent_calls);
Log.i(LOG_TAG, "calling from onCreate()");
cdh = new CallDataHelper(this);
startService(new Intent(this, RatedCallsService.class));
Log.i(LOG_TAG, "Service called.");
Log.i(LOG_TAG, "before call fillList");
/*
* mAdapter = new RecentCallsAdapter();
* getListView().setOnCreateContextMenuListener(this);
* setListAdapter(mAdapter);
*/
fillList();
Log.i(LOG_TAG, "after call fillList");
}
public void onResume() {
super.onResume();
fillList();
}
public void fillList() {
Log.i(LOG_TAG, "entered on fillList");
List<String> ratedCalls = new ArrayList<String>();
ratedCalls = this.cdh.selectTopCalls();
//setListAdapter(new ArrayAdapter<String>(this, R.layout.recent_calls_list_item,
//ratedCalls));
ListView lv = getListView();
lv.setTextFilterEnabled(true);
getListView().setOnCreateContextMenuListener(this);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getApplicationContext(),
((TextView) view).getText(), Toast.LENGTH_LONG).show();
}
});
}
}
Thanks.

It's just a 2 step process:
Create a Layout Xml file which represents 1 item of your list.
Extend Array Adapter and use your custom layout file there. There are several examples on the internet on how to extend Array Adapter.

I'm going to create a listview with multiple textviews.

Related

masterdetail flow with images

I'm very new to developing android apps and my programing experience is also lacking a bit.
But I hope some of you can still help me.
Let's get to my problem.
I created a list with images. If I click on one item, I get a Toast saying "you clicked xy". But I want to include a master detail flow. I looked up the internet for some help but all I could find were tutorials on how to integrate a website...
This is my onCreate method, I hope someone could help me.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CustomList adapter = new
CustomList(MainActivity.this, web, imageId);
list=(ListView)findViewById(R.id.list);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(MainActivity.this, "You Clicked at " + web[+position], Toast.LENGTH_SHORT).show();
}
});
There are two approaches - using fragments or using activities. Fragments are the preferred way, but harder. Seeing as you are new to android you should probably learn how to do it with activities first. Before you can do that you need to learn about intents.
What you need to do is use the intent to start the detail activity when your item is selected.
Master activity
protected void onCreate(Bundle savedInstanceState) {
...
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(MainActivity.this, "You Clicked at " + web[+position], Toast.LENGTH_SHORT).show();
Intent intent = new Intent(MainActivity.this, DetailActivity.class);
//you should make the key string a constant in your code
//im assuming for this example your item is something like a drawable resource id
intent.putExtra("ImageId", getItem(position));
startActivity(intent);
}
});
Detail activity
protected void onCreate(Bundle savedInstanceState) {
...
ImageView iv = (ImageView) findViewById(...);
int imageRes = getIntent().getIntExtra("ImageId", -1);
if (imgRes > 0){
iv.setImageResource(imageRes);
}
}

Using AutoCompleteTextView to change current dispaly page

There is a AutoCompleteTextView and when user write for-example blue and select it from AutoCompleteTextView, the current page change to that particular page.
Here is the code:
public class MainActivity extends Activity {
private AutoCompleteTextView et_search_game;
private TextView TextViewForAutoComplete;
private static String[] GAMES_NAME = new String[] { "blue", "red", "black" };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//AutoCompleteTextView Setting.
et_search_game = (AutoCompleteTextView)findViewById(R.id.actv_search_game_name_xml);
//TextView Setting.
TextViewForAutoComplete = (TextView)findViewById(R.id.tv_for_auto_complete_tv_xml);
ArrayAdapter<String> arrayAdapterForGamesName = new ArrayAdapter<String>(this, android.R.layout.select_dialog_item, GAMES_NAME);
et_search_game.setThreshold(1);
et_search_game.setAdapter(arrayAdapterForGamesName);
et_search_game.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> a, View v, int i, long l) {
// TODO Auto-generated method stub
if(et_search_game.getText().toString().trim()=="blue"){
setContentView(R.xml.blue);
} else if (et_search_game.getText().toString().trim()=="red"){
setContentView(R.xml.red);
} else if (et_search_game.getText().toString().trim()=="black") {
setContentView(R.xml.black);
}
}
});
}
The red,black,blue pages are normal XML files in directory named 'xml'.
After running the code when i write b, the black row display and i click on it but nothing happen.
I don't want to go with activity(intent) method.
thanks.
Instead of == use .equals
Instead of taking value from "et_search_game.getText().toString().trim()" you can take from adapter and position "i"
It is always a best practise to place layout xmls in "layout" directory

How to send data from one activity to another listview?

Hey guys I'm working on an app in android studio. I have a listview and when I make a selection i would like to add that selection to another listview in a different activity. What is the easiest/best way to do this? I've tried putExtra without any luck. Any examples or ideas would be great. Thank you guys.
Thanks for the examples everyone they've helped me understand a lot better the intent system. I've been trying the different examples everyone has posted and I've kind of gotten stuck. The goal is simply to have the items I select from the listview in the Walmart.java file to show up in the listview in GiftsSelected.java I have another place to open the activity so I don't need it to immediately open the new activity.
Here is my code:
This is Walmart.java
public class Walmart extends ActionBarActivity {
private String[]giftarray = {
"Apple" ,
"Bananas",
"Bed",
"Beef",
"Bottle",
"Bread",
"Broccoli",
"Carrots",
"Cat",
"Chicken",
"Chocolate",
"Computer",
"Cow",
"Crow",
"Dog",
"Dolphin",
"Dove",
"Drawer",
"Egg",
"Fish",
"Fork",
"Fridge",
"Giraffe",
};
Intent a = new Intent(Walmart.this,GiftsSelected.class);
private ListView giftListView;
private ArrayAdapter arrayAdapter;
ArrayList<String> list = new ArrayList<String>();
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo){}
public boolean onContextItemSelected(MenuItem item){
return true;
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_walmart);
getSupportActionBar().hide();
giftListView = (ListView) findViewById(R.id.gift_list1);
arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_gallery_item, giftarray );
giftListView.setAdapter(arrayAdapter);
giftListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String item = "Item added to registry";
list.add(item2);
a.putStringArrayListExtra("list",list);
Toast.makeText(getBaseContext(), item, Toast.LENGTH_LONG).show();
}
});
}
This is my GiftsSelected.java code:
public class GiftsSelected extends ActionBarActivity {
private ListView giftListView;
private ArrayAdapter arrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
ArrayList<String> list = new ArrayList<String>();
//This makes my app crash which makes me think I did this wrong...
list = getIntent().getStringArrayListExtra("list");
String[] giftarray = new String[list.size()];
list.toArray(giftarray);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gifts_selected);
getSupportActionBar().hide();
giftListView = (ListView) findViewById(R.id.gift_list1);
arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_gallery_item, giftarray);
giftListView.setAdapter(arrayAdapter);
giftListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String item = "Item added to your registry";
Toast.makeText(getBaseContext(), item, Toast.LENGTH_LONG).show();
}
});
}
this is the list that i use
ArrayList<String> list = new ArrayList<String>();
add elements in it like this
list.add("something");
in first Activity
Intent i=new Intent(FirstActivity.this,SecondActivity.class);
i.putStringArrayListExtra("list",list);
startActivity(i);
in the second activity in the onCreate
list = getIntent().getStringArrayListExtra("list");
Let's say the first Activity is X and X holds a listview that updates another listview in Activity Y.
If X is tightly related to Y, that is to say Y launches X, gets data then immediately returns to Y, then you should use startActivityForResult from Y.
class ActivityY {
public static final int REQUEST_CODE = 2;
...
Intent i = new Intent(this, ActivityX.class);
startActivityForResult(i, REQUEST_CODE);
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE) {
if (resultCode == RESULT_OK) {
String returndata = data.getStringExtra("rowdata");
//update your listView, do notifyDataSetChanged() etc;
}
}
}
}
class ActivityX {
// in listview onItemClickListener or elsewhere that listens to row click
Intent intent = new Intent();
returnIntent.putExtra("rowdata", rowdata); // whatever data you need to transfer
setResult(RESULT_OK,intent);
finish();
}
If X and Y are loosely related, that is to say X is not necessarily launched from Y, but goes to Y then you should just use the usual startActivity(intent).
if X and Y are completely independent, that is to say X is not necessarily launched from Y, may not go to Y or wanders other Activities before arriving in Y then you should cache the data. If the data size is small then the best way is to store it in Preferences. When you Y Activity starts, get the data, update your ListView, then if needed remove the cached data from Preferences.
a)You can make the listview item object parcelable and send it between activities via intent extra.
b)You can save the selected listview item in a global variable.(Not recommended)

Android: Create a new intent with a button from a GridView (GridView with Navigation buttons)

I have created a class of type BaseAdapter that is populated with buttons - when you click on a button I want to load a new intent. This has proven difficult on two levels:
You cannot associate the event with the button (one that creates a new intent) inside the Adapter. This is why I send the Buttons as an array to my Adapter (this solution works, but it is messy)
Even though my buttons are created inside the same Activity - they cannot create a new intent from that Activity. The exeption is so great that I have not even gotten a try...catch statement to work.
I have tried reflection, creating the buttons inside the activity and passing them through, passing the context (to call context.startIntent(...))
My question: can someone show me how to create a ButtonAdapter where each button creates a new Intent - even of the same type as the original Activity?
UPDATE: Here is the code because I am getting answers from people who think I am struggling with onClickListeners:
public class ButtonAdapter extends BaseAdapter
{
private Context _context;
private Button[] _button;
public ButtonAdapter(Context c, Button[] buttons)
{
_context = c;
_button = buttons;
}
// Total number of things contained within the adapter
public int getCount()
{
return _button.length;
}
// Require for structure, not really used in my code.
public Object getItem(int position)
{
return _button[position];
}
// Require for structure, not really used in my code. Can
// be used to get the id of an item in the adapter for
// manual control.
public long getItemId(int position)
{
return position;
}
public View getView(int position, View convertView, ViewGroup parent)
{
_button[position].setId(position);
return _button[position];
}
}
---------------
The Activity:
public class MainActivity extends Activity
{
private GridView _gv;
private TextView _heading;
private ButtonAdapter _adapter;
public void LoadActivity(String heading)
{
try
{
Itent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.putExtra("Level", "NextPage");
intent.putExtra("Heading", heading);
startActivity(intent);
}
catch (Exception ex)
{
Toast.makeText(getApplicationContext(), String.format("Error LoadActivity: %s", ex.getMessage()), Toast.LENGTH_SHORT).show();
}
}
private void createButtonsAdapter(Button _button[])
{
_buttonadapter = new ButtonAdapter(getApplicationContext(), _button);
_gv.setAdapter(_adapter);
}
private void setupButtons()
{
Button[] _buttons = new Button[2];
String names[] = new String[]{"Button1","Button2"};
for (int i = 0; i < 2; i++)
{
_buttons[i] = new Button(this);
_buttons[i].setText(names[i]);
_buttons[i].setTag(names[i]);
_buttons[i].setOnClickListener(new View.OnClickListener()
{
public void onClick(View arg0)
{
try
{
LoadActivity(((Button)arg0).getTag().toString());
}
catch(Exception ex)
{
Toast.makeText(getApplicationContext(), String.format("Error button.onClick: %s", ex.getMessage()), Toast.LENGTH_SHORT).show();
}
}
});
}
createButtonsAdapter(_buttons);
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
_gv = (GridView)findViewById(R.id.gridview);
_heading = (TextView)findViewById(R.id.tv_heading);
Bundle params = getIntent().getExtras();
if (params == null)
{
setupButtons();
}
else if (params.containsKey("Level"))
{
_heading.setText(params.getString("Heading"));
if (params.getString("Level").equals("NextPage"))
{
//code not here yet
}
else if (params.getString("Level").equals("Chapters"))
{
//future code
}
}
}
}
Excuse the bold and caps but I have had enough silly answers to warrent this:
I HAVE TRIED PUTTING THE ONCLICKLISTENER INSIDE THE GRIDVIEW AND IT DOES NOT WORK EITHER
You cannout load an activity from a class outside that activity, even if you pass the context as a parameter. That is why I have resorted to this method, which completely bombs android, even though I have try catch statements.
Please try give me a solution in the form of a correction to my code, other code, or a tutorial that achieves what I want here. I know how to do a button adapter properly, it is the act of loading an Intent that has forced me to implement it this way.
I suggest the following,
Using a common onClick listner for all the buttons in your grid view
Set tag for all the butons in the getView func. of adapter.
Use the tag Object to decide on the intent to fire from the onClick listener.
I hope it helps..
I guess you can easily manipulate your buttons created in your class extending Base adapter. In the getView method .... if you have button b.. then do it as follows
b.setOnClickListener(new OnClickListener()
{
public void onClick()
{
// Do your stuff here ...
}
});
and if you want to start another activity on Click of this button then you need to pass the calling context to this adapter.
Once again I am answering my own question:
http://bottlecapnet.blogspot.com/2012/01/android-buttons-have-no-place-inside.html
I will just have to style TextViews as I want to see them.

Android custom listview, setOnItemSelectedListener not working

I'm just beginning Android development, and I'm working to get a Custom listview with a checkbox working. I've created a base class that extends Activity, Created an Adapter and overrode the getView() method to add the checkbox to the listview. I'm assuming I need to do this because I need something equivalent to didSelectRowIndexAtPath from Obj C to update my model. Please let me know if there's an alternate way of doing this too!
Now in my base class, I have the following code -
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout);
setContentView(R.layout.facilityscreen);
/* Static Data source */
facilityModel = new FacilityDataModel[2];
facilityModel[0] = new FacilityDataModel();
facilityModel[1] = new FacilityDataModel();
facilityModel[0].setFacilityName("Test 1");
facilityModel[0].setFacilityID("Facid0001");
facilityModel[0].setChecked(false);
facilityModel[1].setFacilityName("Test 2");
facilityModel[1].setFacilityID("Facid0002");
facilityModel[1].setChecked(true);
facilityListView = (ListView) findViewById(R.id.facilityListView);
FacilityScreenAdapter adapter = new FacilityScreenAdapter(this, facilityModel);
facilityListView.setAdapter(adapter);
myPatBtn = (Button) findViewById(R.id.myPatBtn);
myPatBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
int i=0;
i++;
}});
facilityListView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
int i=0;
i++;
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
My problem now is the setOnItemSelectedListener isn't getting called at all. Been struggling with this for a couple of hours now, and I can't figure out why it wouldn't get called at all.
Any help is much appreciated!
Thanks,
Teja.
I know this is an outdated answer but I'm going to write it just in case some other fellow who has the same "problem" bumps onto this page :
The solution to the above problem which is not a problem but just a misunderstanding is that the ListView.onItemSelected() event is fired up, upon :
1) Navigating through the emulators-cross handles or
2) as far-as my HTC-Hero is concerned, the rolling-action on the white little roller-ball.
You don't have to extend your activity explicitly to a ListActivity.
Here's my tiny little code which retrieves a phone number from
a TextView control, inside a listview item.
When the user either touches the list item or scrolls through the list with
the little roller-ball the below Events, fire up and MakeACall() method is called :
myList.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View view, int position, long i)
{
TextView myPhone = (TextView)view.findViewById(R.id.txtphone);
MakeACall(myPhone.getText().toString());
}
});
myList.setOnItemSelectedListener(new OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> parent, View view, int position, long i)
{
TextView myPhone = (TextView)view.findViewById(R.id.txtphone);
MakeACall(myPhone.getText().toString());
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
I hope that was helpful... :)
There exists already the possibility to have a ListView with checkboxes.
public class List11 extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_multiple_choice, GENRES));
final ListView listView = getListView();
listView.setItemsCanFocus(false);
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
}
private static final String[] GENRES = new String[] {
"Action", "Adventure", "Animation", "Children", "Comedy", "Documentary", "Drama",
"Foreign", "History", "Independent", "Romance", "Sci-Fi", "Television", "Thriller"
};
}
I've taken this from the APIDemos 'cause it was the simplest. You can then get the selected items by using:
long[] selectedIds = getListView().getCheckItemIds();
What you may also be interested in is the CheckedTextView which is used internally in the list.
To the part of the onListItemClick problem
Try to extend from ListActivity rather than Activity. Then override the onListItemClick. That should work.
use
setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
// here you code
}
})
instead of setOnItemSelectedListener
As setOnItemSelectedListener is called when item is being selected not clicked so to get clicked item you must use setOnItemClickListener this will work
You should set all focusable items in custom list layout to false:
android:focusable="false"
also I think you should not use attributes like android:clickable="true" for them.
The lack of the item selected listener getting called is by design and is based on which mode the device is in. In touch mode, there is no focus and no selection. Your UI should use widgets that differentiate between touch for selection versus touch for scrolling. Radio buttons, for example, are good when there is a single selection choice.

Categories

Resources