How to instantiate an imageview by using if else condition? - android

In my project, I am parsing an XML file. I have used if else condition to print the value in the Log cat. But, I need to know how to instantiate an ImageView by using if else condition. Here is the sample code which I am using.
For example,
if (parentTag.equals("Owners")) {
**it must instantiate an ImageView**
}
Please help. Thanks in advance.
XML:
<Contents>
<Owners>
<Owner>
<Name>Joselito Dimaculangan</Name>
<Age>16</Age>
<EmailAddress>joselito123#gmail.com</EmailAddress>
</Owner>
<Owner>
<Name>Noemi De Galileo</Name>
<Age>14</Age>
<EmailAddress>noemi111#gmail.com</EmailAddress>
</Owner>
</Owners>
<Dogs>
<Dog>
<Name>Barky</Name>
<Birthday>June 29, 2012</Birthday>
</Dog>
<Dog>
<Name>Jumbo</Name>
<Birthday>December 30, 2012</Birthday>
</Dog>
</Dogs>
</Contents>
Main Activity:
while (i.hasNext()) {
dataItem = (ParsedDataSet) i.next();
/*
* parentTag can also represent the main type of data, in
* our example, "Owners" and "Dogs"
*/
String parentTag = dataItem.getParentTag();
Log.v(LOG_TAG, "parentTag: " + parentTag);
if (parentTag.equals("Owners")) {
Log.v(LOG_TAG, "Name: " + dataItem.getName());
Log.v(LOG_TAG, "Age: " + dataItem.getAge());
Log.v(LOG_TAG,
"EmailAddress: " + dataItem.getEmailAddress());
}
else if (parentTag.equals("Dogs")) {
Log.v(LOG_TAG, "Name: " + dataItem.getName());
Log.v(LOG_TAG, "Birthday: " + dataItem.getBirthday());
}
}

If I understand you correctly:
Create the image view in the layout itself, but set it's visibility to 'invisible' or 'gone' depending on how your layout params work.
Then in your condition set the visibility to View.VISIBLE.
Layout
...
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/myImage"
android:src="#drawable/your_image"
android:visibility="invisible"/>
...
Activity
ImageView myView = (ImageView) findViewById(R.id.myImage);
if (parentTag.equals("Owners")) {
myView.setVisibility(View.VISIBLE);
} else {
myView.setVisibility(View.INVISIBLE);
}
or
If you'd like to programatically create the view:
ImageView imageView = new ImageView(this);
LinearLayout.LayoutParams vp =
new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
imageView.setLayoutParams(vp);
imageView.setImageDrawable(ContextCompat.getDrawable(this,R.drawable.myImage));
yourParentView.addView(imageView);

Related

Linearlayout weights not giving what I write

So I want to have a headline that is ALWAYS a third of the screen and then the rest of the 2 thirds of the screen with names. Seems easy but the result is that the headline becomes less than a third if there is many names. It is only 2 lines that does this I wrtite //1 //2 to easily find them but give the whole code since it may affect the result.
Here is a photo.
The top text does not show the whole message and Is not 1 third of the screen as intended
Thanks in advance!
private void showScores() {
float baseTextSize = 100/playerNum;
LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT,
10000.0f //1
);
TextView t = new TextView(this);
String result_msg = getString(R.string.result_msg);
t.setLayoutParams(param);
t.setText(result_msg + "\n");
t.setTextColor(getColor(R.color.white));
if (playerNum>3) {
t.setTextSize(30f);
} else {
t.setTextSize(40f);
}
scoreShower.addView(t);
param.weight = 20000.0f/playerNum; //2
for (int i=0;i<playerNum;i++) {
TextView txt = new TextView(this);
txt.setLayoutParams(param);
if (i == 0) {
txt.setTextSize(baseTextSize + 8f);
txt.setTextColor(getColor(R.color.gold));
} else {
txt.setTextSize(baseTextSize);
txt.setTextColor(getColor(R.color.white));
}
String txtString = (i+1) + ". " + arrayList.get(i).getKey() + " : " + arrayList.get(i).getValue();
txt.setText(txtString);
if (playerNum>6) {
txt.setTextSize(10f);
}
scoreShower.addView(txt);
}
Try using weighted LinearLayout
<LinearLayout
....
...weightSum="3"
...orientation="vertical">
Set the weight of the top view to 2 using
<...
...layout_weight="1">
And the one below set the weight to 2

Removing Single View from a layout programmatically

I'm trying to remove a single view from layout but it is not being removed.
But, when i call removeAll, it does remove them all.
Here is the code:
for (int subspe = 0; subspe < totalSubSpe; subspe++) {
View childSubSpe =
BasicInfoUpdateDocProfile.ll_custom_for_supspecialist.getChildAt(subspe);
TextView subSpecialityId = (TextView) childSubSpe.findViewById(R.id.tv_speciality_id);
TextView specialistId = (TextView) child.findViewById(R.id.tv_id);
String speID = specialistId.getText().toString();
String subSepId = subSpecialityId.getText().toString();
Log.e("TAG", "the the the the id is: speciality " + speID);
Log.e("TAG", "the the the the id is: sub speiciality " + subSepId);
if (speID.equals(subSepId)) {
//removing sub qualificaiton
Log.e("TAG", "It is Equal subspecialist ");
ViewGroup par = (ViewGroup) childSubSpe.getParent();
par.removeView(childSubSpe);
//BasicInfoUpdateDocProfile.ll_custom_for_supspecialist.removeView(childSubSpe);
BasicInfoUpdateDocProfile.ll_custom_for_supspecialist.
removeView((View)childSubSpe.getParent());
// BasicInfoUpdateDocProfile.ll_custom_for_supspecialist.removeAllViews();
}
}

Creating new Textviews in another activity based onClick android

I would like to create a new textview to hold the information sent each time the button is clicked. I have the data I want passing to another screen in a textview but each time i try to put new data it overrides this data because it uses the same textView (textview4). I would like to know if there is a way of creating a new text view to hold my data each time the button is clicked. I hope I was clear enough, thanks.
This code is from a class called CreateWorkout.Java
public void createNewWorkout (View view){
TextView Exercise1TextView = (TextView) findViewById(R.id.Exercise1TextView);
EditText weightEntered = (EditText)findViewById(R.id.WeightLiftedEditText);
EditText reps = (EditText)findViewById(R.id.RepsEditText1);
EditText sets = (EditText)findViewById(R.id.setsEditText1);
Intent getWorkoutIntent = new Intent(this, SelectWorkout.class);
getWorkoutIntent.putExtra("Workout", Exercise1TextView.getText().toString()
+ " " + weightEntered.getText().toString() + "kg"
+ " " + reps.getText().toString() + " reps"
+ " " + sets.getText().toString() + " sets");
startActivity(getWorkoutIntent);
}
This is where the intent is called. This is from SelectWorkout.Java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.select_workout);
TextView textView4 = (TextView) findViewById(R.id.textView4);
textView4.setText(getIntent().getExtras().getString("Workout"));
}
i want to take the data entered here to the next screen. So the exercise name(Leg Press), weight(50), set(3), reps(10)
creating a new text view to hold my data each time
Not an exact answer, but this should guide you in the right direction. You could do something like the following:
Get your bundle
Iterate bundle
Create Textviews during iteration and add them to "your_main_layout" which is the id of the main layout inside select_workout
The bundle is the extra data you're sending over from the Intent. The Iterate is going through each item you sent over to this new intent, the create part refers to creating a TextView for each item you sent over. I've supplied links to what I found below.
Listing all extras of an Intent
//Get a bundle:
for (String key : bundle.keySet()) {
// This is each value (text) you sent over from the last intent
Object value = bundle.get(key);
//output data to log, so you can see what prints out
Log.d(TAG, String.format("%s %s (%s)", key, value.toString(), value.getClass().getName()));
//adding a textview to a layout called your_main_layout (which can be a linear layout or something)
//with value.toString() as the text
your_main_layout.addView(createATextView(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT, RelativeLayout.ALIGN_PARENT_RIGHT,
value.toString(), 20, 10, 20));
}
How can I add a TextView to a LinearLayout dynamically in Android?
//method to create view:
public TextView createATextView(int layout_widh, int layout_height, int align,
String text, int fontSize, int margin, int padding) {
TextView textView_item_name = new TextView(this);
// LayoutParams layoutParams = new LayoutParams(
// LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
// layoutParams.gravity = Gravity.LEFT;
RelativeLayout.LayoutParams _params = new RelativeLayout.LayoutParams(
layout_widh, layout_height);
_params.setMargins(margin, margin, margin, margin);
_params.addRule(align);
textView_item_name.setLayoutParams(_params);
textView_item_name.setText(text);
textView_item_name.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSize);
textView_item_name.setTextColor(Color.parseColor("#000000"));
// textView1.setBackgroundColor(0xff66ff66); // hex color 0xAARRGGBB
textView_item_name.setPadding(padding, padding, padding, padding);
return textView_item_name;
}

programmatically created linearlayout does not wrap content

i am creating linearlayout with programmatically and then i am adding views to it. But the addview function only adding the first row of items(second for loop). How can i fix this issue. I tried to change LinearLayout.LayoutParams.WRAP_CONTENT to 5000px but thats still showing only first item. When i look to logs, for loop is working well.
getChildCount method returning true value in the for loop:
Crashlytics.log(Log.ASSERT, shoppingList.Title + "için: ", linearLayout.getChildCount() + "");
Also i tried to call invalidate and requestlayout methods after for loop but thats still not working.
for(ShoppingList shoppingList : shoppingLists){
LinearLayout linearLayout = new LinearLayout(MainActivity.activity);
containerLL.addView(linearLayout);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(14, 7, 14, 7);
linearLayout.setLayoutParams(layoutParams);
linearLayout.setBackgroundResource(R.drawable.rounded_gray);
for(int i = 0 ; i < shoppingList.shopLists.size() ; i ++){
Crashlytics.log(Log.ASSERT, shoppingList.Title + "için: ", linearLayout.getChildCount() + "");
ShopList shopList = shoppingList.shopLists.get(i);
View v = MainActivity.inflater.inflate(R.layout.row_list, linearLayout, false);
TextView listTitle = (TextView) v.findViewById(R.id.listTitle);
TextView brandTV = (TextView) v.findViewById(R.id.brandTV);
TextView descriptionTV = (TextView) v.findViewById(R.id.descriptionTV);
TextView sizeTV = (TextView) v.findViewById(R.id.sizeTV);
LinearLayout removeLL = (LinearLayout) v.findViewById(R.id.removeLL);
FrameLayout seperatorFL = (FrameLayout) v.findViewById(R.id.seperatorFL);
listTitle.setVisibility(i == 0 ? View.VISIBLE : View.GONE);
listTitle.setText(shoppingList.Title);
descriptionTV.setText(shopList.description);
brandTV.setText(shopList.brandName);
sizeTV.setText(shopList.description);
removeLL.setVisibility(i == shoppingList.shopLists.size() - 1 ? View.VISIBLE : View.GONE);
seperatorFL.setVisibility(i == shoppingList.shopLists.size() - 1 ? View.GONE : View.VISIBLE);
Crashlytics.log(Log.ASSERT, "width : " + v.getWidth() + " " + "height" + v.getHeight(), v.getX() + " X " + " " + v.getY() + " Y ");
linearLayout.addView(v);
}
}
Try adding
linearLayout.setOrientation(LinearLayout.VERTICAL);
Try moving the containerLL.addView(linearLayout); line to after the second for loop.
for(ShoppingList shoppingList : shoppingLists){
LinearLayout linearLayout = new LinearLayout(MainActivity.activity);
.
.
.
for(.....){
.
.
.
}
containerLL.addView(linearlayout);
}

ListView not refreshing after updating object in the list

I've an ArrayList containing Cards. I'm trying to edit a Cards tag in the ArrayList and after editingit I want the ListView to refresh, so the user can see the updated Card, with the new tag.
I'm using cardslib for my Cards. And I'm using Android TagView Lib to tag my cards.
Here's the XML for the Card
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<ImageView
android:id="#+id/colorBorder"
android:layout_width="10dp"
android:layout_height="#dimen/card_base_empty_height"
android:layout_marginTop="2dp"
android:background="#drawable/rectangle" />
<TextView
(...) />
<TextView
(...) />
<TextView
(...) />
<TextView
(...) />
<pl.charmas.android.tagview.TagView
android:id="#+id/tags_view"
android:gravity="center"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_below="#id/card_main_inner_simple_total_contacts"
android:layout_marginLeft="10dp"
android:layout_alignParentRight="true"
android:textSize="12sp"/>
</RelativeLayout>
And here's when I try to edit and update the list view:
private final OnClickCardHeaderPopupMenuListener popupMenuListener = new OnClickCardHeaderPopupMenuListener() {
#Override
public void onMenuItemClick(BaseCard baseCard, MenuItem menuItem) {
final String backupId = baseCard.getId();
switch (menuItem.getItemId()) {
case R.id.action_restore:
BackupsIntentService.restoreCloudBackup(getActivity(), backupId);
Log.d(TAG, "Going to update the card");
setCurrentTask(backupId, "Restoring...", "");
break;
case R.id.action_download:
BackupsIntentService.downloadCloudBackup(getActivity(), backupId);
break;
case R.id.action_delete:
BackupsIntentService.removeCloudBackup(getActivity(), backupId);
break;
}
}
};
And here's the setCurrentTask method, where I update and refresh the list:
private void setCurrentTask(final String backupId, final String currentTaskDescription, final String separator)
{
int pos = -1;
for(int i = 0; i<cloudBackupCardList.size(); i++)
{
BackupCard backupCard = (BackupCard) cloudBackupCardList.get(i);
if(backupCard.getId().equals(backupId))
{
pos = i;
Log.d(TAG, "Found the card at position: " + i + " updating it now");
TagView.Tag[] tags = {new TagView.Tag(currentTaskDescription, Color.BLUE)};
backupCard.setCurrentTaskDescription(tags, separator);
}
}
if(pos == -1)
return;
BackupCard backupCard = (BackupCard) cloudBackupCardList.get(pos);
Log.d(TAG, "There should be: " + currentTaskDescription + " but found: " + backupCard.getCurrentTaskDescription() + " Thread: " + Thread.currentThread()
.getName());
cardListView.setAdapter(new RemoteCardArrayMultiChoiceAdapter(getActivity(), cloudBackupCardList));
// remoteCardArrayMultiChoiceAdapter.remove(remoteCardArrayMultiChoiceAdapter.getItem(pos));
// remoteCardArrayMultiChoiceAdapter.insert(backupCard, pos);
//
//// remoteCardArrayMultiChoiceAdapter.clear();
//// remoteCardArrayMultiChoiceAdapter.addAll(cloudBackupCardList);
// remoteCardArrayMultiChoiceAdapter.notifyDataSetChanged();
// cardListView.refreshDrawableState();
}
I've tried all those (the commented ones) different methods and the list is still not updated.
Here's my logcat output:
07-07 15:12:59.644: D/CardCloudBackupsFragment(24311): Going to update the card
07-07 15:12:59.644: D/CardCloudBackupsFragment(24311): Found the card at position: 8 updating it now
07-07 15:12:59.656: D/CardCloudBackupsFragment(24311): There should be: Restoring... but found: RESTORING... ThreaD: main
As you can see from the logcat, the object is updated but in the listview, on my terminal, it is not. Which leads me to conclude that the listview is not updated/refreshed. (Dont mind the all upper case letters in Restoring, it's expected.)
////////////////////// EDIT ////////////////////////////////
Here is my setupInnerViewElements method as requested in the comments box.
#Override
public void setupInnerViewElements(ViewGroup parent, View view) {
//Retrieve elements
titleTextView = (TextView) parent.findViewById(R.id.card_main_inner_simple_title);
subTitleTextView = (TextView) parent.findViewById(R.id.card_main_inner_simple_sub_title);
TextView descriptionTextView = (TextView) parent.findViewById(R.id.card_main_inner_simple_description);
TextView totalContactsTextView = (TextView) parent.findViewById(R.id.card_main_inner_simple_total_contacts);
tagView = (TagView) parent.findViewById(R.id.tags_view);
if(isLocal)
{
if (titleTextView != null)
titleTextView.setText(TIMESTAMP_TXT + titleCard); // 1st
if (subTitleTextView != null)
subTitleTextView.setText(CONTACTS_COUNT_TXT + subTitleCard); // 2nd
if(descriptionTextView != null)
descriptionTextView.setText(RESTORE_COUNT_TXT + description); // 3rd
if(tagView != null)
{
TagView.Tag[] tags = {new TagView.Tag("Wow", Color.TRANSPARENT)};
tagView.setTags( tags, "" );
}
return;
}
if (titleTextView != null)
titleTextView.setText(TIMESTAMP_TXT + titleCard); // 1st
if (subTitleTextView != null)
subTitleTextView.setText(PHONE_BRAND_TXT + subTitleCard); // 2nd
if(descriptionTextView != null)
descriptionTextView.setText(PHONE_MODEL_TXT + description); // 3rd
if(totalContactsTextView != null)
totalContactsTextView.setText(CONTACTS_COUNT_TXT + contactsNumber); // 4th
if(tagView != null)
{
TagView.Tag[] tags = {new TagView.Tag("Wow", Color.TRANSPARENT)};
tagView.setTags( tags, "" );
}
}
Replace below Line:
cardListView.setAdapter(new RemoteCardArrayMultiChoiceAdapter(getActivity(), cloudBackupCardList));
with
RemoteCardArrayMultiChoiceAdapter adapter=new RemoteCardArrayMultiChoiceAdapter(getActivity(), cloudBackupCardList));
cardListView.setAdapter(adapter);
adapter.notifyDataSetChanged();
Thats it...
The problem was a no problem at all, it was as simply as setting the tag and the TagsLibrary would take care of updating the CardView. I just didn't know this so I was trying to refresh the listview.
So I simply have this method on my card class:
public void setCurrentTaskDescription(TagView.Tag[] tags, String separator)
{
tagView.setTags(tags, separator);
}
and then on my listener I just do this:
switch ( menuItem.getItemId()) {
case R.id.action_restore:
BackupsIntentService.restoreCloudBackup(getActivity(), backupId);
EventBus.getDefault().post(new
setCurrentTask(backupCard, "Restoring...", "");
break;
}
private void setCurrentTask(final BackupCard backupCard, final String currentTaskDescription, final String separator)
{
TagView.Tag[] tags = {new TagView.Tag(currentTaskDescription, Color.GREEN)};
backupCard.setCurrentTaskDescription(tags, separator);
}
No need to refresh the list!
I was trying to make a thunderstorm inside a glass of water. Lesson learned.

Categories

Resources