How can I add a Total TextView inside ListView, as well as a Save Button under the ListView, dynamically?
Total is to be displayed similar to the following image. (note: not my data representation)
Activity A (Code Snippet)
long as=0; // for total
long bs=0;
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
// receive from B
switch (requestCode)
{
case 0:
result = data.getStringExtra("text"); // holds value (34,24)
name = data.getStringExtra("a"); // Project
as = as+Long.parseLong(result); // For total amount
Text = " " + name + " " + "RM" + result + ""; // display in listView
if (mClickedPosition == -1) {
//add new list
m_listItems.add(Text);
m_listBitmapItems.add(Global.img);
} else {
// edit listView value and image
m_listItems.set(mClickedPosition, Text);
m_listBitmapItems.set(mClickedPosition, Global.img);
}
adapter.notifyDataSetChanged();
listV.setAdapter(adapter);
break;
case 1: // Another name
result = data.getStringExtra("text");
name = data.getStringExtra("a");
description = data.getStringExtra("c");
bs = bs + Long.parseLong(result);
Log.d("FIRST", "result:" + result);
Text = " " + name + " " + "RM" + result + "";
if (mClickedPosition == -1)
{
m_listItems.add(Text);
} else {
m_listItems.set(mClickedPosition, Text);
}
adapter.notifyDataSetChanged();
listV.setAdapter(adapter);
break;
}
}
long samount = as + bs;
Toast.makeText(getActivity(), samount + "", Toast.LENGTH_LONG).show();
}
Activity A (Rendered Output)
Here I would like to add a Total TextView with value 58 (output as RM58), as well as a Save Button.
I am using the following xml files.
a.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="#string/text"
android:textSize="20sp" />
<ListView android:id="#+id/listView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
claims.xml (inside the listView)
<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<TextView android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:textAppearance="?android:attr/textAppearanceMedium" />
<ImageView android:id="#+id/imageView4"
android:layout_width="101dp"
android:layout_height="50dp" />
</AbsoluteLayout>
Thanks.
Add the following footer.xml file to res/layout http://developer.android.com/reference/android/widget/ListView.html
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent
android:orientation="vertical" >
// Format as you please
<TextView
android:id="#+id/tv"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="Total" />
</LinearLayout>
In your activity create and initialise the following variables.
LayoutInflater inflater = getLayoutInflater();
ViewGroup footer = (ViewGroup) inflater.inflate(R.layout.footer, listView,
false);
// You can add this when an item is added and remove it if the list is empty.
listView.addFooterView(footer, null, false);
tv = (TextView)footer.findViewById(R.id.tv);
// Update the text.
tv.append("t/"+ results.toString());
As mentioned in the comments, you can either use long total as a static class member and update it with the results value total+=results; taking care to reset the value to zero or decrement it if an item is removed from the list.
The other way is to loop through the items in your list, parsing the items to the object and getting the particular value of type long from each object and summing them as you go.
As you are now able to dynamically add your button, I'll add briefly for other users browsing, set the buttons visibility to GONE, so that the element does not displace the layout when it is not visible, HIDDEN makes the element not visible, but the space taken by the element affects the layout (and sometimes this is useful). Then the button visibility is dynamically changed to VISIBLE when an item is added to the list, and back to GONE when the list is cleared.
<Button
android:id="#+id/btn"
android:text="button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"/>
http://developer.android.com/reference/android/transition/Visibility.html
Related
Hello i need Your help in displaying data from database in activity, ive been trying many things but have no idea how to do that. Im creating some kind of weather app. It has Data in Database on the device.
There is DataBaseHandler Class which returns List with all Spots.
public List<Spot> getUserSpotList(int id){
List<Spot> spotList = new ArrayList<Spot>();
String selectQuery = "SELECT " +SPOT_ID+","+ SPOT_NAME + ","+ SPOT_LATITUDE + ","+SPOT_LONGITUDE+","+SPOT_WIND_SPEED +","+SPOT_WEATHER_ICON+
" FROM " + TABLE_SPOT + " WHERE "+SPOT_USER_ID + "="+id;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
Spot spot = new Spot();
spot.setSpot_id(Integer.parseInt(cursor.getString(0)));
spot.setSpotName(cursor.getString(1));
spot.setSpotLatitude(cursor.getString(2));
spot.setSpotLongitude(cursor.getString(3));
spot.setWindSpeed(Double.parseDouble(cursor.getString(4)));
spot.setSpotWeatherIcon(cursor.getString(5));
// Adding User to list
spotList.add(spot);
} while (cursor.moveToNext());
}
return spotList;
}
And i Have Activity with listView xml in witch i want to display some stuff from the code above based on another relativelayout for one element.
SpotActivity.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.example.mk.rcwindy.SpotActivity">
<ListView
android:id="#+id/listLajout"
android:layout_width="wrap_content"
android:layout_height="400dp"
android:layout_weight="1"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
And here is Relative layout for one element in the list view above.
I would like to connect SpotName from database with TextView id=SpotName, Windspeed from database with Windspeed Text View, and Display image in ImageView based on SpotWeatherIcon from database.
spotlista_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:padding="6dip"
android:id="#android:id/list">
<ImageView
android:id="#+id/SpotAvilabilityIcon"
android:layout_width="20dp"
android:layout_height="match_parent"
android:background="#color/green_apple"/>
<ImageView
android:id="#+id/WeatherIcon"
android:layout_width="70dp"
android:layout_height="match_parent"
android:layout_toLeftOf="#+id/WindSpeed"
android:scaleType="centerInside"
/>
<TextView
android:id="#+id/WindSpeed"
android:text=""
android:textSize="30dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toLeftOf="#+id/WindSpeedUnit"
android:layout_gravity="center"
android:layout_centerVertical="true"/>
<TextView
android:text="m/s"
android:textSize="30dp"
android:id="#+id/WindSpeedUnit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_centerVertical="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<FrameLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentTop="true"
android:layout_marginLeft="10dp"
android:layout_toRightOf="#+id/SpotAvilabilityIcon"
android:layout_toStartOf="#+id/WeatherIcon"
android:layout_toLeftOf="#+id/WeatherIcon"
android:layout_centerVertical="true">
<TextView
android:id="#+id/SpotName"
android:text=""
android:textSize="40dp"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:layout_centerVertical="true"/>
</FrameLayout>
</RelativeLayout>
And here is the code of activity SpotActivity
public class SpotActivity extends ActionBarActivity {
int loggedUserId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_spot);
Intent intent = getIntent();
if (null != intent) {
loggedUserId = intent.getIntExtra("logged", 0);
}
String text = "logged user id = "+loggedUserId;
Toast t1 = Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT);
t1.show();
}
public int userIdSender(){
return loggedUserId;
}
#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_spot, 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_new){
Intent intent = new Intent(this, SpotAddActivity.class);
intent.putExtra("logged",loggedUserId);
startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
Thanks for Help! I tried to do that and still have a big problems so now im asking for help. Its a school project im working at and that is the last thing i have to do to make the app work-Display stuff :D
You need to create an adapter for your ListView. I recommend you watch The World Of ListView.
All an adapter does is provide a view for each item in your data set. For cursor data, you should subclass CursorAdapter and implement the newView() and bindView() methods at the minimum.
I'm new to android and I'm working on an app for few weeks.
As the title says, the problem that I have is when I want to programmatically set a Spinner to GONE, a ListView that is below it in a RelativeLayout is also gone.
Here is the xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Spinner
android:id="#+id/tableSelector"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<ListView
android:id="#+id/insertList"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/tableSelector"
android:layout_above="#+id/saveButton"
android:background="#aaffffff"
android:divider="#11000000"
android:dividerHeight="4dp"
android:visibility="gone" >
</ListView>
<Button
android:id="#+id/saveButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:text="#string/button_save"
android:visibility="visible" />
</RelativeLayout>
And here is how I set it programmatically:
switch(spinnerFlag)
{
case SPINNER_HIDDEN: tableSelector.setVisibility(View.GONE); break;
case SPINNER_VISIBLE: tableSelector.setVisibility(View.VISIBLE); break;
case SPINNER_VISIBLE_DISABLED: tableSelector.setVisibility(View.VISIBLE);
tableSelector.setEnabled(false);
break;
default: Log.d("onActivityCreated - InserFragment", "Spinner flag < " + spinnerFlag + " > does not exist. Spinner is now visible enabled.");
}
This works fine for case SPINNER_VISIBLE and SPINNER_VISIBLE_DISABLED, but when setting it to SPINNER_HIDDEN the ListView also dissapears.
UPDATED
As Psy Duck and Nguyen Doan Tung suggested I added the layout_alignWithParentIfMissing attribute to the ListView. However i noticed it still didn't work. I set the visibility of ListView to visible in the xml and it is displayed, but it's empty.
So it solved the problem that I was having, but I have another problem now with the ListView being empty (I'll mention again that when the (spinnerFlag == SPINNER_VISIBLE || spinnerFlag == SPINNER_VISIBLE_DISABLED), it works just fine)
Here is a larger part of my code:
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
insertList = (ListView) getActivity().findViewById(R.id.insertList);
/* Some code */
tableSelector = (Spinner) getActivity().findViewById(R.id.tableSelector);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_dropdown_item,tables);
tableSelector.setAdapter(adapter);
tableSelector.setOnItemSelectedListener(new OnItemSelectedListener() {
/* Some code containing some Log.d() */
});
/* Some code */
Log.d("Insert fragment", "Setting table selected by position in list " + pos + ", " + tName);
tableSelector.setSelection(pos); // pos is calculated correctly in the code i didn't show
switch(spinnerFlag)
{
case SPINNER_HIDDEN: tableSelector.setVisibility(View.GONE); break;
case SPINNER_VISIBLE: tableSelector.setVisibility(View.VISIBLE); break;
case SPINNER_VISIBLE_DISABLED: tableSelector.setVisibility(View.VISIBLE);
tableSelector.setEnabled(false);
break;
default: Log.d("onActivityCreated - InserFragment", "Spinner flag < " + spinnerFlag + " > does not exist. Spinner is now visible enabled.");
}
}
The Log before the tableSelector.setSelection(pos) is shown in the LogCat, but none of the Logs from the tableSelector.onItemSelected(); is displayed, so the setSelection doesn't call it.
Any ideea why this might be? (I was thinking that setting aView to GONE might stop it functionality, but I setSelection() before setting it to GONE)
Thank you!
FIXED
Instead of:
tableSelector.setVisibility(View.GONE); break;
I used the workaround:
tableSelector.setVisibility(View.VISIBLE);
tableSelector.setEnabled(false);
ViewGroup.LayoutParams params = (ViewGroup.LayoutParams) tableSelector.getLayoutParams();
params.height = 0;
tableSelector.setLayoutParams(params);
break;
And it now works as I needed it.
You need to add this line to your listview android:layout_alignWithParentIfMissing="true"
<ListView
android:id="#+id/insertList"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/tableSelector"
android:layout_above="#+id/saveButton"
android:background="#aaffffff"
android:divider="#11000000"
android:dividerHeight="4dp"
android:layout_alignWithParentIfMissing="true"
android:visibility="gone" >
</ListView>
When a view is set to GONE it doesn't take any space in the layout. Your ListView has this attr android:layout_below="#+id/tableSelector" which will look for Spinner to set ListView below it.
To avoid that you could simply add the line android:layout_alignWithParentIfMissing="true" to your ListView, in that way it will ignore looking for Spinner when it's missing and will cover it's place as well. Hope it helps.
I am trying to implement card text change on Sony SmartEyeglass, but I am having trouble with the layouts. I adopted the advanced layout sample from the SDK and modified it.
I have a default xml layout that displays a title and a body text. I put 'Title' and 'Body' as default strings in the xml file, and tried to update the title and body as 'Updated' and 'Updated body text'. However, the result shows me the default layout (with 'Title' and 'Body') and the text 'Updated body text' overlapping on top of them.
Why is the title not edited, and how come the body text is on top of the xml TextView?
Here is the relevant code:
#Override
public void onResume() {
showingDetail = false;
ControlListItem item = createControlListItem(namePosition);
showLayout(item.dataXmlLayout, null);
sendListCount(item.layoutReference, quotedPeople.size());
sendListPosition(item.layoutReference, namePosition);
//utils.sendTextViewLayoutId(R.id.names_body);
sendListItem(item);
}
private ControlListItem createControlListItem(final int position) {
Log.d(Constants.LOG_TAG, "position = " + position);
ControlListItem item = new ControlListItem();
item.layoutReference = R.id.names_gallery;
item.dataXmlLayout = R.layout.smarteyeglass_quotes_names_gallery;
item.listItemId = position;
item.listItemPosition = position;
List<Bundle> list = new ArrayList<Bundle>();
// Header data
Bundle headerBundle = new Bundle();
headerBundle.putInt(Control.Intents.EXTRA_LAYOUT_REFERENCE, R.id.names_title);
headerBundle.putString(Control.Intents.EXTRA_TEXT, "Updated");
list.add(headerBundle);
// Body data
Bundle bodyBundle = new Bundle();
bodyBundle.putInt(Control.Intents.EXTRA_LAYOUT_REFERENCE, R.id.names_body);
bodyBundle.putString(Control.Intents.EXTRA_TEXT, "Updated body title");
list.add(bodyBundle);
item.layoutData = list.toArray(new Bundle[list.size()]);
return item;
}
Here is the xml layout file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="#dimen/smarteyeglass_control_width"
android:layout_height="#dimen/smarteyeglass_control_height"
tools:ignore="PxUsage,UselessParent,HardcodedText" >
<TextView
android:id="#+id/names_title"
android:layout_width="400px"
android:layout_height="30px"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginTop="5px"
android:paddingLeft="6px"
android:background="#android:color/black"
android:text="Title"
android:textColor="#android:color/white"
android:textSize="#dimen/smarteyeglass_text_size_normal" />
<View
android:id="#+id/names_divider"
android:layout_width="400px"
android:layout_height="2px"
android:layout_alignParentLeft="true"
android:layout_below="#+id/names_title"
android:background="#android:color/white" />
<TextView
android:id="#+id/names_body"
android:layout_width="400px"
android:layout_height="78px"
android:layout_marginTop="5px"
android:layout_marginLeft="10px"
android:layout_alignParentLeft="true"
android:layout_below="#+id/names_divider"
android:textColor="#android:color/white"
android:textSize="#dimen/smarteyeglass_text_size_small"
android:text="Body" />
<Gallery
android:id="#+id/names_gallery"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
</Gallery>
</RelativeLayout>
we just tested your example and the text is changing fine. It looks like you might have picked the wrong XML for the gallery item. You started with smarteyeglass_layout_test_gallery instead using smarteyeglass_item_gallery.
This is the attendance_sheet.xml file where the number of check boxes is calculated by retrieving the number of students in the 'student_login' table. The name of the check box also should be from the table.
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="match_parent" >
<TableLayout
android:layout_width="match_parent"
android:layout_height="match_parent" >
<CheckBox
android:id="#+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" XYZ" />
<CheckBox
android:id="#+id/checkBox2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" PQR" />
<Button
android:id="#+id/bUpdateAttendance"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Submit Attendance" />
</TableLayout>
</ScrollView>
in DbHelper.class
private static final String STUDENT_TABLE_CREATE = "CREATE TABLE "
+ STUDENT_TABLE + "( s_id INTEGER PRIMARY KEY AUTOINCREMENT , "
+ "s_name TEXT NOT NULL , s_pass TEXT NOT NULL , "
+ "s_roll_no TEXT NOT NULL , " + "s_email TEXT NOT NULL);";
TeacherloggedInPage.java
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.attendancesheet);
Bundle extras = getIntent().getExtras();
if (savedInstanceState == null) {
extras = getIntent().getExtras();
if (extras == null) {
t_id = (String) null;
} else {
t_id = extras.getString("key");
}
} else {
t_id = (String) savedInstanceState.getSerializable("key");
}
UpdateAttendanceButton = (Button) findViewById(R.id.bUpdateAttendance);
UpdateAttendanceButton.setOnClickListener(this);
}
Here is what you needs to do ,
1) Create checkbox dynamically.
2) On based on names from Database , give checkBox names.
3) add them into your Layout(May be LinearLayout)
Here is the similar answer How to add CheckBoxes Dynamically
your Layout xml should be like below
<Linear Layout With orientation Vertical>
<Linear Layout with Orientation Vertical /> // Add CheckBoxes in this Layout, By taking its ID in the code.
<Update BUtton>
</Linear Layout closing for top LL>
I'm a noob to android development and I am having trouble instantiating an ImageView within a ViewPager. My ViewPager has 7 pages and all of them have ImageViews. However, only the ImageView on the first page instantiates and doesn't return null when called. I checked repeatedly to be certain that each viewpager page is referencing the correct xml and am certain that each corresponding xml has the appropriate ImageView. Any help is greatly appreciated.
MY CODE
Working viewpager page.
case 0:
resId = (R.layout.reference_layout);
view = inflater.inflate(resId, null);
herb_ListView = (IndexableListView)view.findViewById(R.id.herbList);
herbsListresource = res.getStringArray(R.array.herblist);
herbsItems = new ArrayList<String>();
Collections.addAll(herbsItems, herbsListresource);
Collections.sort(herbsItems);
ArrayAdapter<String> herbs_adapter = new CustomListAdapter(ReferenceActivity.this, R.layout.list_item_herbs);
for (int i=0; i<herbsItems.size();i++)
herbs_adapter.add(herbsItems.get(i));
herb_ListView.setAdapter(herbs_adapter);
herb_ListView.setFastScrollEnabled(true);
herb_ListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, final View view, int position, long id) {
View toolbar = view.findViewById(R.id.toolbar);
String herb_info = herb_ListView.getItemAtPosition(position).toString() + "_info";
String new_herb_info = herb_info.replaceAll("\\s+", "").replace("'", "").replace(".", "");
Log.e("herb_info result", new_herb_info);
String herb_pic = herb_ListView.getItemAtPosition(position).toString().toLowerCase() + "_picture";
String new_herb_pic = herb_pic.replaceAll("\\s+", "").replace("'", "").replace(".", "");
Log.e("herb_pic result", new_herb_pic);
try{
((ImageView)view.findViewById(R.id.herb_image)).setImageResource((ReferenceActivity.this.getResources().getIdentifier(new_herb_pic, "drawable", ReferenceActivity.this.getApplicationInfo().packageName)));
((TextView)view.findViewById(R.id.herb_description)).setText((ReferenceActivity.this.getResources().getIdentifier(new_herb_info, "string", ReferenceActivity.this.getApplicationInfo().packageName)));
}catch(Exception e){
Log.e("Herb Info Error", "Error loading Herb Info >> " + e.getMessage() + " //" + e.toString());
}
//Setting Arrows
if(((ImageView)view.findViewById(R.id.chevron)).getTag()=="down"||((ImageView)view.findViewById(R.id.chevron)).getTag()==null){
((ImageView)view.findViewById(R.id.chevron)).setImageResource(R.drawable.chevron_white);
((ImageView)view.findViewById(R.id.chevron)).setTag("up");
}else{
((ImageView)view.findViewById(R.id.chevron)).setImageResource(R.drawable.chevron_white_down);
((ImageView)view.findViewById(R.id.chevron)).setTag("down");
}
// Creating the expand animation for the item
ExpandAnimation expandAni = new ExpandAnimation(toolbar, 500);
// Start the animation on the toolbar
toolbar.startAnimation(expandAni);
}
});
((ViewPager) collection).addView(view, 0);
return view;
Non-working viewpager page.
case 4:
resId = (R.layout.reference_layout);
view = inflater.inflate(resId, null);
crystals_ListView = (IndexableListView)view.findViewById(R.id.herbList);
crystalsListresource = res.getStringArray(R.array.crystallist);
crystalsItems = new ArrayList<String>();
Collections.addAll(crystalsItems, crystalsListresource);
Collections.sort(crystalsItems);
ArrayAdapter<String> crystals_adapter = new CustomListAdapter(ReferenceActivity.this, R.layout.list_item_crystals);
for (int i=0; i<crystalsItems.size();i++)
crystals_adapter.add(crystalsItems.get(i));
crystals_ListView.setAdapter(crystals_adapter);
crystals_ListView.setFastScrollEnabled(true);
crystals_ListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, final View view, int position, long id) {
View toolbar = view.findViewById(R.id.crystal_toolbar);
String crystal_sign = crystals_ListView.getItemAtPosition(position).toString() + "_definition";
String new_crystal_sign = crystal_sign.replaceAll("\\s+", "").replace("'", "").replace(".", "").replace("(", "").replace(")", "");
Log.e("crystal_sign result", new_crystal_sign);
String crystal_mode = crystals_ListView.getItemAtPosition(position).toString() + "_optimumday";
String new_crystal_mode = crystal_mode.replaceAll("\\s+", "").replace("'", "").replace(".", "").replace("(", "").replace(")", "");
Log.e("crystal_mode_result", crystal_mode);
String crystal_usage = crystals_ListView.getItemAtPosition(position).toString() + "_usage";
String new_crystal_usage = crystal_usage.replaceAll("\\s+", "").replace("'", "").replace(".", "").replace("(", "").replace(")", "");
Log.e("crystal_usage_result", new_crystal_usage);
try{
TextView crystalSign = (TextView)view.findViewById(R.id.crystal_sign);
TextView crystalMode = (TextView)view.findViewById(R.id.crystal_mode);
TextView crystalUsage = (TextView)view.findViewById(R.id.crystal_usage);
crystalSign.setText("Sign: " +(ReferenceActivity.this.getResources().getIdentifier(new_crystal_sign, "string", ReferenceActivity.this.getApplicationInfo().packageName)));
crystalMode.setText("Mode: " +(ReferenceActivity.this.getResources().getIdentifier(new_crystal_mode, "string", ReferenceActivity.this.getApplicationInfo().packageName)));
crystalUsage.setText("Usage: " +(ReferenceActivity.this.getResources().getIdentifier(new_crystal_usage, "string", ReferenceActivity.this.getApplicationInfo().packageName)));
}catch(Exception e){
Log.e("Crystal Info Error", "Error loading Crystal Info >> " + e.getMessage() + " //" + e.toString());
}
//Setting Arrows
ImageView chevron = (ImageView)view.findViewById(R.id.crystal_chevron);
if(chevron.getTag()=="down"||chevron.getTag()==null){ //NULLPOINTER THROWN HERE.
chevron.setImageResource(R.drawable.chevron_white);
chevron.setTag("up");
}else{
chevron.setImageResource(R.drawable.chevron_white_down);
chevron.setTag("down");
}
// Creating the expand animation for the item
ExpandAnimation expandAni = new ExpandAnimation(toolbar, 500);
// Start the animation on the toolbar
toolbar.startAnimation(expandAni);
}
});
((ViewPager) collection).addView(view, 0);
return view;
Non-working viewpager xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal" >
<TextView
android:id="#+id/crystal_title"
android:layout_width="275dp"
android:layout_height="wrap_content"
android:focusable="false"
android:focusableInTouchMode="false"
android:padding="20dip"
android:textSize="20dp" />
<ImageView
android:id="#+id/crystal_chevron"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="30dp"
android:focusable="false"
android:focusableInTouchMode="false"
android:src="#drawable/chevron_white_down"
android:layout_gravity="right"
android:padding="20dip"/>
</LinearLayout>
<!-- *********************** -->
<!-- *** TOOLBAR LAYOUT **** -->
<!-- *********************** -->
<LinearLayout
android:id="#+id/crystal_toolbar"
android:layout_width="fill_parent"
android:layout_height="150dip"
android:layout_marginBottom="-50dip"
android:orientation="vertical"
android:visibility="gone" >
<TextView
android:id="#+id/crystal_sign"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:focusable="false"
android:focusableInTouchMode="false"
android:padding="2dip"
android:text="No information available" />
<TextView
android:id="#+id/crystal_mode"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:focusable="false"
android:focusableInTouchMode="false"
android:padding="2dip"
android:text="No information available" />
<TextView
android:id="#+id/crystal_usage"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:focusable="false"
android:focusableInTouchMode="false"
android:padding="2dip"
android:text="No information available" />
</LinearLayout>
I don't have any hard proof for this but my thoughts on why only views within the first fragment in the ViewPager can be found is because the others do not "exist." Sure, they exist in XML, but I don't know that all layouts are inflated and matinatined once the Fragments are added such that you can update them directly if the UI is not visible (or at all).
I also do not think you can use findViewById to reach a view within a Fragment hosted by your ViewPager. findViewById only looks within the content view supplied - i.e. the layout for that activity - or a specific layout you supply to it - e.g. if you inflate a particular layout, like that of a list item, and then call findViewById on that to find a view inside, like a TextView. You should not be able to just call findViewById on a view for some Fragment and change it.
As to fixing the problem. Your views should be initialized within the fragments themselves. If you're tring to update the view in the fragment based on something that occurs in your FragmentActivity then I would try this
(1) Keep a reference to the fragments you are adding to your ViewPager
Private whateverFragment f1
//initialize onCreate
f1= new WhateverFragment();
(2) Declare a public method in that fragment you can use to update the view you want. Note the view is initialized within the fragment not the host activity.
public updateTextView(String idk){
TextView message = (TextView)getActivity().findViewById(R.id.message);
message.setText(idk);
}
(3) if you want to know the update is complete, or commuicate back from the fragment to the fragment activity, just use an interface. The easiest way to do it is to declare an interface in your fragment, implement that interface in the host activity, and initialize the interface within the fragments onAttach method. This way you can callback between the fragment and its host activity.
Using this approach you can pretty much control everything within your fragment from the activity containing the view pager