I have method CreateView, which dynamically creates View and fill them with data from SharedPrefernces file.
First for (File loadFile : loadFiles) work correctly. It fills data in fields in created View that 100% are in the file SharedPrefernces.
Second for (Map.Entry entry : usersPresets.getAll().entrySet()). It fills data in created Views, but not the fact that they are in SharedPrefences file. And here I got problem.
public void CreateView(File[] loadFiles) {
if (presetsStorage.exists()) {
for (File loadFile : loadFiles) {
//noinspection SpellCheckingInspection
if (!loadFile.getName().contains("userpreset_")) {
//noinspection UnnecessaryContinue
continue;
} else {
if (loadFile.isFile()) {
String presetsName = loadFile.getName();
presetsName = presetsName.substring(0, presetsName.length() - 4);
usersPresets = getSharedPreferences(presetsName, MODE_PRIVATE);
presetsContainer = (LinearLayout) findViewById(R.id.presetsContainer);
View userPresetsView = getLayoutInflater()
.inflate(R.layout.preset_fragment, presetsContainer, false);
userPresetsView.findViewById(R.id.presetFragMenubtn)
.setOnClickListener(viewClickListener);
((CircularSeekBar) userPresetsView.findViewById(R.id.presetFragA)).
setProgress(usersPresets.getInt("a", 0));
((CircularSeekBar) userPresetsView.findViewById(R.id.presetFragB)).
setProgress(usersPresets.getInt("b", 0));
((CircularSeekBar) userPresetsView.findViewById(R.id.presetFragC)).
setProgress(usersPresets.getInt("c", 0));
TextView presetFragName = (TextView) userPresetsView
.findViewById(R.id.userPresetName);
presetFragName.setText(presetsName);
presetFragName.setOnClickListener(viewClickListener2);
presetsContainer.addView(userPresetsView);
presetFragName.setText(presetsName.substring(11));
//HERE I HAVE A PROBLEM
for (Map.Entry<String, ?> entry : usersPresets.getAll().entrySet()) {
if (arr.contains(entry.getKey())) {
// noinspection UnnecessaryContinue
continue;
} else {
CardView flavor_cardView = (CardView) findViewById(R.id.flavor_cardView);
final View usersFlavorsPreset = getLayoutInflater()
.inflate(R.layout.preset_userflavor_fragment, flavor_cardView, false);
((TextView) usersFlavorsPreset.findViewById(R.id.tvUserFlavorPresetName))
.setText(entry.getKey());
((TextView) usersFlavorsPreset.findViewById(R.id.tvUserFlavorPresetValue)).
setText(String.valueOf(entry.getValue()));
flavor_cardView.addView(usersFlavorsPreset);
}
}
}
}
}
}
}
I need that would, at presence of this data, created a new row, depending on the amount of data in the SharedPrefernces. Now, it works, but creates only one row and the values rewrites and displays only the data that were in the last iteration of the passage of second for.
Screenshots, where I tried to explain the problem:
View - screenshot
Content of aaa.xml - screenshot 2
Content of test.xml - screenshot 3
Tell me please, where I need to place for that would have the values not overwritten in the same location.
I hope that explained at least a little understandable. If you do not know - I will try to describe the problem again.
UPDATE: I added to the CardView the LinearLayout, and all the elements are now displayed in one place. So another question - how to place them in the right box?
for (Map.Entry<String, ?> entry : usersPresets.getAll().entrySet()) {
if (arr.contains(entry.getKey())) {
// noinspection UnnecessaryContinue
continue;
} else {
LinearLayout flavor_linear = (LinearLayout) findViewById(R.id.flavor_linear);
final View usersFlavorsPreset = getLayoutInflater().
inflate(R.layout.preset_userflavor_fragment, flavor_linear, false);
((TextView) usersFlavorsPreset.
findViewById(R.id.tvUserFlavorPresetName)).setText(entry.getKey());
((TextView) usersFlavorsPreset.
findViewById(R.id.tvUserFlavorPresetValue)).setText(String.valueOf(entry.getValue()));
flavor_linear.addView(usersFlavorsPreset);
}
}
Related
My goal is to add my custom view inside LinearLayout.I have custom arrayList and I would to add custom views with for loop.Here is a my code snippet
public void replaceCustomView() {
for (int i = 0; i < insertDataItems().size(); i++) {
final LayoutInflater inflater = LayoutInflater.from(this);
final View reView = inflater.inflate(R.layout.item_parent_child_listing, null, false);
final TextView parentName = reView.findViewById(R.id.tv_parentName);
final ImageView headerImageView = reView.findViewById(R.id.header_imageView);
final LinearLayout linearLayout_childItems = reView.findViewById(R.id.ll_child_items);
final RelativeLayout headerLayout = reView.findViewById(R.id.header_layout);
final RelativeLayout headerImageLayout = reView.findViewById(R.id.header_image_layout);
parentName.setText(insertDataItems().get(i).getParentName());
if (insertDataItems().get(i).getChildDataItems() != null) {
headerImageLayout.setVisibility(View.VISIBLE);
headerImageLayout.setVisibility(View.VISIBLE);
for (int j = 0; j < insertDataItems().get(i).getChildDataItems().size(); j++) {
final LayoutInflater childInflater = LayoutInflater.from(this);
final View childView = childInflater.inflate(R.layout.z_history_child_item, null, false);
final TextView key = childView.findViewById(R.id.u_key);
final TextView value = childView.findViewById(R.id.u_value);
key.setText(insertDataItems().get(i).getChildDataItems().get(j).getKey());
value.setText(insertDataItems().get(i).getChildDataItems().get(j).getValue());
linearLayout_childItems.addView(childView);
}
} else {
headerImageLayout.setVisibility(View.GONE);
headerLayout.setBackgroundColor(Color.parseColor("#e8e8e8"));
}
linearLayout_childItems.setVisibility(View.GONE);
if (insertDataItems().get(i).getParentName().length() > 0) {
if (insertDataItems().get(i).isAllowDisable()) {
headerImageView.setVisibility(View.GONE);
linearLayout_childItems.setVisibility(View.VISIBLE);
} else {
headerImageView.setVisibility(View.VISIBLE);
linearLayout_childItems.setVisibility(View.GONE);
}
} else {
linearLayout_childItems.setVisibility(View.VISIBLE);
headerLayout.setVisibility(View.GONE);
}
replaceLayout.post(() -> replaceLayout.addView(reView));
}
}
I call this function like this
runOnUiThread(() -> replaceCustomView());
Custom views adding successfully,but my problem is that in a first time activity is slowly.Android need to much time to add view.My custom array's size is 20.Is it a any way to add views step by step ,not add all views each time?
What's a best practice ?
thanks
Please do not use the concept of adding runtime components when the items are more. This will cause the activity to share the memory with view rendering logic and you'll be able to recycle the views. this kind of implementation can be used only when there are a few (may be 2 to 5) items and can't be achieved with recyclerview due to some UI limitations.
Hence use a RecyclerView to load the items and you can use the concept of adding custom items inside a child item to achieve this functionality.
So I was able to have my textViews drag and drop properly. But when I close the application and re-open it doesn't save the position of the new textViews. In a previous application I was able to save data using SharedPreferences but I couldn't quite get it to work in this scenario. Any insight or help would be appreciated!
Thanks,
DragLinearLayout dragDropAndroidLinearLayout = (DragLinearLayout) findViewById(R.id.drag_drop_layout);
for (int i = 0; i < dragDropAndroidLinearLayout.getChildCount(); i++) {
View child = dragDropAndroidLinearLayout.getChildAt(i);
dragDropAndroidLinearLayout.setViewDraggable(child, child);
}
The code I'm using to implement the drag and drop feature. I guess I'm not sure what part in this code would I use to put into the SharedPreferences if that's the way I would even do it.
Try using setTag and getTag
for(i=0;i<5;i++){
final View items= View.inflate(this, R.layout.yourItemStyle, null);
items.setTag(i);
final TextView text1= (TextView) note.findViewById(R.id.textView1);
text1.setId(i);
dragLinearLayout.addDragView(items, text1,i);
dragLinearLayout.setOnViewSwapListener(new DragLinearLayout.OnViewSwapListener() {
#Override
public void onSwap(View firstView, int firstPosition, View secondView, int secondPosition) {
int ID= Integer.parseInt(String.valueOf(firstView.getTag()))
String strID = String.valueOf(ID);
Log.v("ID",strID );
}
});
}
I'm using a custom adapter with clickable items inside.The problem is that when i'm scrolling listview it re-runs my codes which exist in item click.
How can i disable listview doing this?
Here is an example of my adapter:
public override View GetView(int position, View convertView, ViewGroup parent)
{
View row = convertView;
if (row == null)
{
row = LayoutInflater.From(mContext).Inflate(Resource.Layout.InventoryPreview, null, false);
}
TextView txtInventoryName = row.FindViewById<TextView>(Resource.Id.txtInventoryName);
Button ExtraBtn = row.FindViewById<Button>(Resource.Id.ExtrasBtn);
txtInventoryName.Click += (sender, e) =>
{
var db = new SQLiteConnection(Connection.dpPath);
db.CreateTable<OrderPreviewClass>();
OrderPreviewClass tbl = new OrderPreviewClass();
Connection.InventoryItemID = mitems[position].InventoryItemID;
Connection.InventoryItemName = mitems[position].InventoryItemName;
Connection.RetailPrice = mitems[position].InventoryItemPrice;
Connection.Quantity = "1";
tbl.CategoryID = Connection.CategoryID;
tbl.InventoryItemID = Connection.InventoryItemID;
tbl.Description = Connection.InventoryItemName;
tbl.Quantity = Connection.Quantity;
tbl.Price = Connection.RetailPrice;
tbl.ExtrasPrice = "0";
tbl.RealPrice = Connection.RetailPrice;
tbl.Extras = ",";
db.Insert(tbl);
Toast toast = Toast.MakeText(mContext, "x1 " + txtInventoryName.Text, ToastLength.Short);
toast.Show();
};
ExtraBtn.Click += (sender, e) =>
{
Connection.InventoryItemID = mitems[position].InventoryItemID;
Connection.InventoryItemName = mitems[position].InventoryItemName;
Connection.RetailPrice = mitems[position].InventoryItemPrice;
Toast toast = Toast.MakeText(mContext, txtInventoryName.Text, ToastLength.Short);
toast.Show();
mContext.StartActivity(typeof(ExtrasPreviewMain));
};
return row;
}
How can i stop to re-run my code every time listview is scrolling? Should i use ClickListener?
The reason is that your cells get recycled, so every time the cell is recycled you are adding another event to the text control and button - events in C# are multicast delegates, so can fire multiple things.
Every time a cell is recycled another event handler is added.
The easies fix would be to extract both handlers into methods or local functions instead of lambdas, and always remove the handler before adding.
Something like:
void TextHandler(object sender, EventArgs args) =
{
var db = new SQLiteConnection(Connection.dpPath);
... // rest of the handler here
}
// remove the handler - doesn't matter if it's not already set
txtInventoryName.Click -= TextHandler;
// set the handler
txtInventoryName.Click += TextHandler;
I have the following code which is inside my Fragment to display all files in the folder in a listview. I also added the function to delete files from the listview. Once the last file is deleted I would like to display a different xml layout, which successfully works, if the tab is changed but not real time if the last item from the listview is deleted.
mFrame3 = (RelativeLayout) inflater.inflate( R.layout.ptrip, container, false ); //display if file exist
noFilesDisplayed = (RelativeLayout) inflater.inflate(R.layout.nofile, container, false); //display if file doesn't exist
if (FilesInFolder != null) {
mFrame3.setVisibility(View.VISIBLE); //display the listview
noFilesDisplayed.setVisibility(View.GONE); //hide it
}
else {
mFrame3.setVisibility(View.GONE); //hide it
noFilesDisplayed.setVisibility(View.VISIBLE); //display if no file exist in the folder
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
int menuItemIndex = item.getItemId();
String[] menuItems = getResources().getStringArray(R.array.menuSelect);
String menuItemName = menuItems[menuItemIndex];
String txt = ((TextView) info.targetView.findViewById(R.id.txtTitle)).getText().toString();
if (menuItemIndex == 0) {
if (folder.exists()) {
//File flEachFile = new File(folder.toString() + "/" + currentFileName + ".tp");
flEachFile = new File(folder.toString() + "/" + txt + ".tp");
flEachFile2 = new File(folder.toString() + "/." + txt + ".tp");
if (flEachFile.exists()) {
flEachFile.delete();
}
if (flEachFile2.exists()) {
flEachFile2.delete();
}
adapter.remove(adapter.getItem(info.position));
adapter.notifyDataSetChanged();
dataList.setEmptyView(noFilesDisplayed);
//getActivity().getActionBar().setSelectedNavigationItem(1);
}
}
return true;
}
What's not happening is once the last item is deleted from the listview, the following command isn't changing the view: dataList.setEmptyView (noFilesDisplayed);
How do i achieve the view change once the last file is displayed? Maybe refresh the Tab view itself?
Actually, setEmptyView() is meant to only be called once when creating the ListView.
Set the noFilesDisplayed visibility to GONE and don't modify it manually, the ListViewwill do it for you. Maybe that'll solve the problem.
Also, someone says here that manually adding the inflated view to the ListView's parent (instead of providing the parent when calling inflate()) solved their similar problem.
I have a LinearLayout which I've looped a number of new Button objects into. How do I go about clearing that div correctly (eg removing all the buttons)? I've tried a number of times (unsuccessfully) to do this, but have nothing to show for it.
** edit **
I'm not sure if this helps, but in flex/AS3 I would do something like:
while(myView.numChildren) myView.removeChildAt(0);
** a little code **
View col1 = findViewById(R.id.col1);
for(final Map.Entry<String,HashMap<String,String>> entry : _nav.entrySet()) {
Button item = new Button(this);
item.setText(entry.getKey());
item.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
openCol2(entry);
}
});
((LinearLayout) col1).addView(item);
}
private final void openCol2(Map.Entry<String,HashMap<String,String>> entry) {
View col2 = findViewById(R.id.col2);
// here is where I want to clean out col2. Right before I add more buttons.
for(int i = 0; i < _nav.size(); ++i) {
Button item = new Button(this);
//item.setText(entry.getKey());
((LinearLayout) col2).addView(item);
}
}
Try this
LinearLayout col2 = (LinearLayout)findViewById(R.id.col2);
col2.removeAllViews();
Assumption: R.id.col2 is of LinearLayout type else to make it more generic typecast it to ViewGroup. Hope this help!!!