I am working in a fragment. When the fragment is called it inflates a layout. Which all works.
v = createTreeView( inflater, container, savedInstanceState);
On my action bar I have a search button which Onclicks changes the layout
btnSearch.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
v = createFliterLivstView( linflate, VContainer);
count = 1;
Log.i("Create","creating tree view kind of ");
}
});
Both views work separately, but when I move the createFilterListView to the OnClick functions it does nothing. The Log has been processed which means it is running through. It just is not inflating the layout.
Below is the onCreateView
#Override
public View onCreateView( LayoutInflater inflater, ViewGroup container, final Bundle savedInstanceState) {
linflate = inflater;
VContainer = container;
m_Context = inflater.getContext();
thisApp = (ThisApp)getActivity().getApplicationContext();
v = createTreeView( inflater, container, savedInstanceState);
FragmentActivity actionBar = getActivity();
View d = actionBar.getActionBar().getCustomView().findViewById(R.id.btn_search);
ImageButton btnSearch = (ImageButton)d.findViewById(R.id.btn_search);
btnSearch.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
v = createFliterLivstView( linflate, VContainer);
count = 1;
Log.i("Create","creating tree view kind of ");
}
});
View b = actionBar.getActionBar().getCustomView().findViewById(R.id.btn_cancel_search);
ImageButton btnCancelSearch = (ImageButton)b.findViewById(R.id.btn_cancel_search);
btnCancelSearch.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
v = createTreeView( linflate, VContainer, savedInstanceState);
}
});
return v;
}
Any help would be greatly appreciated. Thank you in advance.
private View createFliterLivstView( LayoutInflater inflater, ViewGroup container){
View v1 = linflate.inflate(R.layout.list_main, VContainer, false);
historyContainer = (FrameLayout)v1.findViewById(R.id.history_container_layout);
FragmentActivity actionBar = getActivity();
View d = actionBar.getActionBar().getCustomView().findViewById(R.id.txtSearch);
EditText filterEditText = (EditText)d.findViewById(R.id.txtSearch);
filterEditText.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
Log.i("anish", s.toString());
historyContainer.removeAllViews();
final List<String> tempHistoryList = new ArrayList<String>();
tempHistoryList.addAll(historyList);
for(String data : historyList) {
if(data.indexOf(s.toString()) == -1) {
tempHistoryList.remove(data);
}
}
viewStub = new ViewStub(getActivity().getBaseContext(), R.layout.history_schedule);
viewStub.setOnInflateListener(new ViewStub.OnInflateListener() {
#Override
public void onInflate(ViewStub stub, View inflated) {
setUIElements(inflated, tempHistoryList);
}
});
historyContainer.addView(viewStub);
viewStub.inflate();
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
setViewStub();
return v1;
}
Below is the CreateTreeView
private View createTreeView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View v = inflater.inflate(R.layout.layout_list_symptoms, container, false);
makeList();
Button btnNext = (Button)v.findViewById(R.id.btn_next);
btnNext.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
String bsafe = thisApp.app_pref.getString("BSAFE", "0");
if(bsafe==null || bsafe.equalsIgnoreCase("0")) {
thisApp.app_edit.putString("SYMTOMS", "");
thisApp.app_edit.commit();
}
Set<Long> sel = fancyAdapter.selected;
Iterator<Long> it = sel.iterator();
boolean hasDone = false;
int i = 0;
while(it.hasNext()) {
Long longId = it.next();
//Log.i(TAG, "...id = " + longId);
final Integer[] hierarchy = fancyAdapter.getManager().getHierarchyDescription(longId);
// 5678
WorkVO vo = list.get(longId.intValue());
try {
pnObj.put("value" , jsonArr.put(vo.getName()) );
//i++;
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
hasDone = true;
}
jsonSymptoms.put(pnObj);
Log.i("Symtoms ", " json="+ jsonSymptoms.toString());
thisApp.app_edit.putString("SYMTOMS", jsonSymptoms.toString());
thisApp.app_edit.commit();
if(hasDone) {
if(bsafe!=null && bsafe.equalsIgnoreCase("1")) {
mCallback.onNextWork(DefinedConstants.FRAG_BSAFE_REPORT);
} else {
mCallback.onNextWork(DefinedConstants.FRAG_FATIGUE_RATING);
}
} else {
Toast.makeText(getActivity(), "Please make a selection", 0).show();
}
}
});
TreeType newTreeType = null;
boolean newCollapsible;
if (savedInstanceState == null) {
manager = new InMemoryTreeStateManager<Long>();
final TreeBuilder<Long> treeBuilder = new TreeBuilder<Long>(manager);
for (int i = 0; i < NODES.length; i++) {
treeBuilder.sequentiallyAddNextNode((long) i, NODES[i]);
}
//Log.d(TAG, manager.toString());
newTreeType = TreeType.FANCY;
newCollapsible = true;
} else {
manager = (TreeStateManager<Long>) savedInstanceState
.getSerializable("treeManager");
if (manager == null) {
manager = new InMemoryTreeStateManager<Long>();
}
newTreeType = (TreeType) savedInstanceState
.getSerializable("treeType");
if (newTreeType == null) {
newTreeType = TreeType.SIMPLE;
}
newCollapsible = savedInstanceState.getBoolean("collapsible");
}
treeView = (TreeViewList) v.findViewById(R.id.mainTreeView);
fancyAdapter = new FancyColouredVariousSizesAdapter(getActivity(), selected,
manager, LEVEL_NUMBER, job_kind, list);
simpleAdapter = new SimpleStandardAdapter(getActivity(), selected, manager,
LEVEL_NUMBER, job_kind, list);
setTreeAdapter(newTreeType);
setCollapsible(newCollapsible);
registerForContextMenu(treeView);
manager.collapseChildren(null);
return v;
}
Inflate a view with this method.
View v = View.inflate(m_context,R.layout.yourlayout,null);
The createView method returns a View which sets the view for the fragment. What you are doing in the onClick is creating a view that isn't overriding your fragments main view.
To be honest it would be much easier and would require less state logic if on click you replaced the Fragment with a new Fragment with the layout you wanted.
Having a Fragment that handles two separate layouts is harder to maintain and to keep the correct state. Not to mention will make the class much larger.
Related
I'm implementing an application in which user can store Debit Cards and later they can use it by just entering the CVV number of the same card. I have used RecyclerView for all the items(Debit Cards) stored by the user. Everything is working fine, view is rendering all good and I have used LinearLayoutManager to show Horizontal scroll.
Now the problem which I am facing is whenever I try to enter CVV of any card as soon as I click on it the view gets shifted towards the last item of the list of Stored Cards, So if I'm having three cards stored in my list and I try to enter CVV for the first one the view is shifting directly to the third card but the focus remains on the first cards EditText. I don't know what's going on with the same. I'm sharing some code part for the same.
Setting adapter and defining horizontal scroll :-
recyclerAdapter = new RecyclerStoredCardAdapter(mContext, storedCards);
LinearLayoutManager layoutManager
= new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
storedCardListRecycler.setLayoutManager(layoutManager);
storedCardListRecycler.setVisibility(View.VISIBLE);
storedCardListRecycler.setAdapter(recyclerAdapter);
Sharing the screenshots with this so it will get clear. Any help would be appreciable. Thanks.
I have did this using ListView not with RecyclerView
But you can do with RecyclerView also.
Here is my used class demo.
SettingItemListViewAdapter.java
/**
* Created by vishalchhodwani on 18/10/16.
*/
public class SettingItemListViewAdapter extends BaseAdapter {
private final String TAG = "SettingItemListViewAdapter";
Context context;
List<SettingListViewItem> settingItemList;
OnMyClickListeners onMyClickListeners;
MyDatabaseAdapter myDatabaseAdapter;
public SettingItemListViewAdapter(Context context, List<SettingListViewItem> settingItemList) {
this.context = context;
this.settingItemList = settingItemList;
myDatabaseAdapter = new MyDatabaseAdapter(context);
}
public void setMyClickListener(OnMyClickListeners onMyClickListeners) {
this.onMyClickListeners = onMyClickListeners;
}
#Override
public int getCount() {
return settingItemList.size();
}
#Override
public Object getItem(int position) {
return settingItemList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.setting_listview_item, parent, false);
holder.settingListViewForm = (RelativeLayout) convertView.findViewById(R.id.settingListViewItem_form1);
holder.vrijeTekst = (EditText) convertView.findViewById(R.id.settingListViewItem_ed_virje_row1);
holder.kenteken = (EditText) convertView.findViewById(R.id.settingListViewItem_ed_kenketen_row1);
holder.checkRow = (ImageView) convertView.findViewById(R.id.settingListViewItem_check_row1);
holder.deleteRow = (ImageView) convertView.findViewById(R.id.settingListViewItem_deleteRow);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.vrijeTekst.setText(settingItemList.get(position).getItemVrijeTekst());
holder.kenteken.setText(settingItemList.get(position).getItemKenteken());
boolean isSelected = settingItemList.get(position).isItemSelected();
holder.checkRow.setImageResource(isSelected ? R.drawable.checked : R.drawable.uncheked);
holder.vrijeTekst.setTag(position);
holder.vrijeTekst.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(final View v, boolean hasFocus) {
try {
if (!hasFocus) {
if (settingItemList.size() > 0) {
int position = (int) v.getTag();
EditText Caption = (EditText) v;
settingItemList.get(position).setItemVrijeTekst(Caption.getText().toString());
}
} else {
EditText caption = (EditText) v;
caption.setCursorVisible(true);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
holder.kenteken.setTag(position);
holder.kenteken.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(final View v, boolean hasFocus) {
try {
if (!hasFocus) {
if (settingItemList.size() > 0) {
int position = (int) v.getTag();
EditText Caption = (EditText) v;
settingItemList.get(position).setItemKenteken(Caption.getText().toString());
}
} else {
EditText caption = (EditText) v;
caption.setCursorVisible(true);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
holder.checkRow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (myDatabaseAdapter.isAvailableInTable(settingItemList.get(position).getItemId()))
onMyClickListeners.onSelectButtonClicked(position);
}
});
holder.deleteRow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onMyClickListeners.onDeleteItemButtonClicked(position);
}
});
if (getCount() == position + 1) {
holder.vrijeTekst.requestFocus();
holder.vrijeTekst.performClick();
}
return convertView;
}
public static class ViewHolder {
RelativeLayout settingListViewForm;
EditText vrijeTekst, kenteken;
ImageView checkRow, deleteRow;
}
}
SettingN_New.java (It is a fragment)
public class SettingN_New extends Fragment implements OnClickListener, OnMyClickListeners {
private final String TAG = "SettingN_New";
Context context;
private TextView tv_demo;
ToggleButton togglebtn_save;
Button btn_save, btn_add;
ListView settingItemListView;
List<SettingListViewItem> settingItemList;
SettingItemListViewAdapter settingItemListViewAdapter;
MyDatabaseAdapter myDatabaseAdapter;
TinyDB loginpref;
boolean isNewRowAdded = true;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//This line of code will stay focus on selected edittext in list
getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST);
ActionBar bar = getActivity().getActionBar();
bar.show();
View rootView = inflater.inflate(R.layout.setting_new, container, false);
initializeViews(rootView);
setUI();
getListOfItems();
return rootView;
}
private void setUI() {
try {
if (loginpref.getBoolean(ConstantLib.PREF_AUTO_LOGIN)) {
togglebtn_save.setChecked(true);
} else {
togglebtn_save.setChecked(false);
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
private void initializeViews(View rootView) {
context = getActivity();
LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View headerView = inflater.inflate(R.layout.setting_listview_header, null);
btn_save = (Button) headerView.findViewById(R.id.btn_save);
btn_add = (Button) headerView.findViewById(R.id.btn_add);
togglebtn_save = (ToggleButton) headerView.findViewById(R.id.togglebtn_save);
tv_demo = (TextView) headerView.findViewById(R.id.tv_demo);
settingItemList = new ArrayList<>();
settingItemListView = (ListView) rootView.findViewById(R.id.setting_listView);
settingItemListView.setClickable(true);
settingItemListView.refreshDrawableState();
settingItemListView.addHeaderView(headerView);
settingItemListView.setItemsCanFocus(true);
settingItemListViewAdapter = new SettingItemListViewAdapter(context, settingItemList);
settingItemListViewAdapter.setMyClickListener(this);
settingItemListView.setAdapter(settingItemListViewAdapter);
myDatabaseAdapter = new MyDatabaseAdapter(context);
loginpref = new TinyDB(getActivity());
btn_save.setOnClickListener(this);
btn_add.setOnClickListener(this);
tv_demo.setOnClickListener(this);
togglebtn_save.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
loginpref.putBoolean(ConstantLib.PREF_AUTO_LOGIN, isChecked);
}
});
}
private void getListOfItems() {
settingItemList.clear();
settingItemList.addAll(myDatabaseAdapter.getAllData());
if (settingItemList.size() == 0) {
isNewRowAdded = true;
SettingListViewItem settingListViewItem = new SettingListViewItem();
settingListViewItem.setItemId(settingItemList.size() + "");
settingListViewItem.setItemVrijeTekst("");
settingListViewItem.setItemKenteken("");
settingListViewItem.setItemSelected(false);
settingItemList.add(settingListViewItem);
} else {
isNewRowAdded = false;
}
notifyDataSetChanged();
}
private void hideKeyboard() {
// Check if no view has focus:
View view = getActivity().getCurrentFocus();
if (view != null) {
InputMethodManager inputManager = (InputMethodManager) getActivity()
.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(view.getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_save:
clearFocus();
hideKeyboard();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
if (isValidationSuccess())
saveAllData();
}
}, 200);
break;
case R.id.btn_add:
addAnotherRow();
break;
case R.id.tv_demo:
clickedOnTvDemo();
break;
}
}
private void clickedOnTvDemo() {
try {
Intent i = new Intent(getActivity(), Setting_exp_activity.class);
startActivity(i);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
private boolean isValidationSuccess() {
Log.e(TAG, "isValidationSuccess() called : settingItemList.size()==" + settingItemList.size());
for (int i = 0; i < settingItemList.size(); i++) {
if (settingItemList.get(i).getItemVrijeTekst().equalsIgnoreCase("") || settingItemList.get(i).getItemKenteken().equalsIgnoreCase("")) {
showToast("Veld mag niet leeg zijn");// showToast("Fields should not be empty!!");
return false;
}
}
return true;
}
private void saveAllData() {
Log.e(TAG, "saveAllData() called");
myDatabaseAdapter.clearTable();
for (int i = 0; i < settingItemList.size(); i++) {
isNewRowAdded = false;
SettingListViewItem settingListViewItem = new SettingListViewItem();
settingListViewItem.setItemId(i + "");
settingListViewItem.setItemVrijeTekst(settingItemList.get(i).getItemVrijeTekst());
settingListViewItem.setItemKenteken(settingItemList.get(i).getItemKenteken());
settingListViewItem.setItemSelected(settingItemList.get(i).isItemSelected());
myDatabaseAdapter.insertDataToTable(settingListViewItem);
}
DialogUtils.showInfoDialog(getActivity(),
"Instellingen opgeslagen");
}
private void addAnotherRow() {
Log.e(TAG, "addAnotherRow() called");
if (settingItemList.size() > 0 && !isNewRowAdded) {
if (!settingItemList.get(settingItemList.size() - 1).getItemVrijeTekst().equalsIgnoreCase("") && !settingItemList.get(settingItemList.size() - 1).getItemKenteken().equalsIgnoreCase("")) {
isNewRowAdded = true;
Log.e(TAG, "addAnotherRow() called check 1");
SettingListViewItem settingListViewItem = new SettingListViewItem();
settingListViewItem.setItemId(settingItemList.size() + "");
settingListViewItem.setItemVrijeTekst("");
settingListViewItem.setItemKenteken("");
settingListViewItem.setItemSelected(false);
settingItemList.add(settingListViewItem);
notifyDataSetChanged();
} else {
Log.e(TAG, "addAnotherRow() called check 2");
showToast("Al toegevoegd");// showToast("Already Added!!");
}
} else {
if (!isNewRowAdded) {
isNewRowAdded = true;
Log.e(TAG, "addAnotherRow() called check 3");
SettingListViewItem settingListViewItem = new SettingListViewItem();
settingListViewItem.setItemId("0");
settingListViewItem.setItemVrijeTekst("");
settingListViewItem.setItemKenteken("");
settingListViewItem.setItemSelected(false);
settingItemList.add(settingListViewItem);
notifyDataSetChanged();
} else {
Log.e(TAG, "addAnotherRow() called check 4");
showToast("Al toegevoegd");// showToast("Already Added!!");
}
}
settingItemListView.setSelection(settingItemList.size());
Log.e(TAG, "addAnotherRow() called check 5");
Log.e(TAG, "after settingItemList.size()==" + settingItemList.size());
}
#Override
public void onDeleteItemButtonClicked(int position) {
Log.e(TAG, "onDeleteItemButtonClicked() position==" + position);
if (myDatabaseAdapter.getAllData().size() > 0)
showAlertForDeleteItem(position);
else
showToast("Er is geen item te verwijderen"); // showToast("No item to Delete");
}
#Override
public void onSelectButtonClicked(int position) {
Log.e(TAG, "onSelectButtonClicked() position==" + position);
for (int i = 0; i < settingItemList.size(); i++) {
Log.e(TAG, "onSelectButtonClicked() called check 3");
settingItemList.get(i).setItemSelected(false);
}
settingItemList.get(position).setItemSelected(true);
notifyDataSetChanged();
}
private void showAlertForDeleteItem(final int position) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setMessage("Weet je zeker dat je dit item wilt wissen?");//alertDialog.setMessage("Are you sure you want to delete this item?");
// ja==yes
alertDialog.setPositiveButton("Ja", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
myDatabaseAdapter.deleteTableRow(settingItemList.get(position).getItemId() + "");
settingItemList.remove(position);
settingItemListViewAdapter.notifyDataSetChanged();
if (settingItemList.size() == position + 1) {
isNewRowAdded = false;
}
if (settingItemList.size() == 0) {
isNewRowAdded = false;
addAnotherRow();
}
}
});
//Annuleer==cancel
alertDialog.setNegativeButton("Annuleer", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.show();
}
private void notifyDataSetChanged() {
settingItemListViewAdapter.notifyDataSetChanged();
}
private void showToast(String message) {
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
}
public void clearFocus() {
if (getActivity().getWindow().getCurrentFocus() != null) {
getActivity().getWindow().getCurrentFocus().clearFocus();
}
}
}
I am giving you my whole class. why? Because it will give you more understanding that how I used it with ListView.
Test it and Let me know. :)
Note
This line of code is very important - getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST);
Not able to reproduce this issue. Let me know if the following code does what you are facing. If not, can provide more feedback if you share you Adapter's Code.
MainActivity.java
public class MainActivity
extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
MyAdapter adapter = new MyAdapter();
recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
recyclerView.setAdapter(adapter);
}
}
public class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_ite, parent);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
((EditText)((MyViewHolder)holder).mBinding.findViewById(R.id.editText)).setHint(position + " ");
}
#Override
public int getItemCount() {
return 100;
}
public class MyViewHolder extends RecyclerView.ViewHolder {
View mBinding;
public MyViewHolder(View binding) {
super(binding);
this.mBinding = binding;
}
}
}
The 2xml layouts:
<EditText
android:id="#+id/editText"
android:layout_height="200dp"
android:layout_width="300dp"/>
</android.support.v7.widget.CardView>
My main_activity.xml is as follows:
<RelativeLayout
android:layout_height="match_parent"
android:layout_width="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_height="wrap_content"
android:layout_width="match_parent"/>
</RelativeLayout>
As you can see this is the simplest case. Let me know if I missed anything.
I have made a list view that shows the contents in the database. But if I add data in the database via a different activity then the modified list view is visible only when I close and then start my app.
So how do I refresh my List view so that as soon as the data is entered, it is visible in the list.
I have heard of notifyDataSetChange() but don't know where to put it in my code.
Please help. The TimePickerPop class is the class that adds data to the database.
public class MainActivityFragment2 extends Fragment {
private List<TimeList> TDList = new ArrayList<TimeList>();
public MainActivityFragment2() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
populateTimeList();
}
private void populateTimeList() {
Context ctx = this.getActivity();
DBoperations db = new DBoperations(ctx);
Cursor cr = db.getInformation(db);
cr.moveToFirst();
String TimeH, TimeM, EtimeH, EtimeM;
do {
TimeH = Integer.toString(cr.getInt(1));
TimeM = Integer.toString(cr.getInt(2));
EtimeH = Integer.toString(cr.getInt(3));
EtimeM = Integer.toString(cr.getInt(4));
TDList.add((new TimeList(TimeH + " : " + TimeM, EtimeH + " : " + EtimeM)));
}while (cr.moveToNext());
}
private class MyAdapter extends ArrayAdapter<TimeList> {
public MyAdapter(Context context, List<TimeList> values) {
super(context, R.layout.time_list_item,values);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
LayoutInflater inflater = LayoutInflater.from(getContext());
if( v == null){
v = inflater.inflate(R.layout.time_list_item, parent, false);
}
TimeList currLoc = TDList.get(position);
TextView theTextView = (TextView) v.findViewById(R.id.time_list_item_textview1);
theTextView.setText(currLoc.getTime());
theTextView = (TextView) v.findViewById(R.id.time_list_item_textview2);
theTextView.setText(currLoc.getDuration());
return v;
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.time_list_view, container, false);
ListView list = (ListView) rootView.findViewById(R.id.time_list_view);
ArrayAdapter<TimeList> adapter = new MyAdapter(getActivity(),TDList);
list.setAdapter(adapter);
//adapter.notifyDataSetChanged(); // not working
setRetainInstance(true);
ImageButton ib = (ImageButton) rootView.findViewById(R.id.imageButton1);
ib.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivityFragment2.this.getActivity(), TimePickerPopup.class));
}
});
return rootView;
}
}
This is the TimePickerPopup class.
public class TimePickerPopup extends Activity {
Context ctx =this;
private TimePicker time_picker1;
private TimePicker time_picker2;
private ImageButton select_time1;
private ImageButton select_time2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.time_picker);
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int width = dm.widthPixels;
int height = dm.heightPixels;
getWindow().setLayout((int) (width * .8), (int) (height * .7+50));
time_picker1 = (TimePicker) findViewById(R.id.timePicker1);
time_picker2 = (TimePicker) findViewById(R.id.timePicker2);
select_time1 = (ImageButton) findViewById(R.id.selectButton1);
select_time2 = (ImageButton) findViewById(R.id.selectButton2);
select_time1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getBaseContext(),"Start time " + time_picker1.getCurrentHour() + " : " + time_picker1.getCurrentMinute(), Toast.LENGTH_SHORT).show();
ScrollView sv1 = (ScrollView) findViewById(R.id.sv);
sv1.fullScroll(View.FOCUS_DOWN);
}
});
select_time2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getBaseContext(),"End time " + time_picker2.getCurrentHour() + " : " + time_picker2.getCurrentMinute(), Toast.LENGTH_SHORT).show();
DBoperations db = new DBoperations(ctx);
db.putInfo(db, time_picker1.getCurrentHour(), time_picker1.getCurrentMinute(), time_picker2.getCurrentHour(), time_picker2.getCurrentMinute(), 0, 0);
finish();
}
});
}
}
in your adapter create :
public void notifyChange() {
notifyDataSetChanged();
}
and from your activity call :
adapter.notifyChange();
I have a listView of items.Each item has two separate fragment inside it and gets visible when the item is clicked. Inside a fragment there is another ListView and a button. The button displays a dialog through which ListView inside the fragment gets populated.The problem is when the dialog closes,the parent listview gets refreshed and as a result fragment visibility is gone. I have to click the parent list view item again to see the fragment and its content. I want the Fragment view and its updated content remain viewed after the dialog is dismissed. So someone please help me in it.
The following is my parent listView class:
#SuppressLint("NewApi")
public class Due extends FragmentActivity implements
OutletformAddDialog_due.DonebuttonListener {
TextView headerView;
View tempstore, imagetempstore;
OutletformAddDialog_due selectedOutlet;
Fragment fr;
public BaseAdapter dueadapter;
ListView Duelist;
Boolean DuedetailFlag = false, OrderdetailFlag = false;
TextView DueDetailsRight, DueDetailsTop, DueDetailsBottom,
DueDetailsrightHorizontal, OrderDetailsleft, OrderDetailstop,
OrderDetailsBottom, OrderDetailsleftHorizontal, DueDetailsButton,
OrderDetailsButton, btnDueNav, tvOutletName;
Button DuetoCallCard;
int index;
public int getIndex() {
return index;
}
private String order_id;
private String outlet_id;
private String amount;
private String date;
private int count = 0;
private View lvNavigation;
boolean formDashboard = false;
ArrayList<Payment> dueArray = new ArrayList<Payment>();
ArrayList<DueItem> tempdueArray = new ArrayList<DueItem>();
ArrayList<String> navigationList;
NavigationAdapter adapter;
int prevItem, currentItem;
View btnDuetoCallCard;
private ImageView home;
String stateStore = "";
TextView totalCollectedDue;
TextView orderDueAmmount;
ViewGroup header;
private View clickedHeaderView;
FragmentManager fm;
FragmentTransaction fragmentTransaction;
public String getheaderDueamount() {
return orderDueAmmount.getText().toString();
}
public void setheaderDueamount(String amount) {
orderDueAmmount.setText(amount);
}
// public void setDueList(int position) {
// dueadapter.getItem(position)
// }
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.duea_amount_layout);
DuetoCallCard = (Button) findViewById(R.id.btnDuetoCallCard);
DuetoCallCard.bringToFront();
Duelist = (ListView) findViewById(R.id.due_layout_listView);
tvOutletName = (TextView) findViewById(R.id.textviewoutletname);
home = (ImageView) findViewById(R.id.btndueHome);
home.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(new Intent(Due.this,
MainActivity.class));
intent.putExtra("home", true);
startActivity(intent);
}
});
Bundle b = getIntent().getExtras();
if (b != null) {
formDashboard = getIntent().getExtras().getBoolean("fromDashboard");
}
if (formDashboard) {
// spinRoute.setVisibility(View.VISIBLE);
// spinOutlet.setVisibility(View.VISIBLE);
// Outlet1542
selectedOutlet = new OutletformAddDialog_due();
selectedOutlet.show(getFragmentManager(), "dialog");
} else {
populateArray();
}
btnDuetoCallCard = findViewById(R.id.btnDuetoCallCard);
initArrays();
// for disappearing the big circular button
Duelist.setOnScrollListener(new OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
if (firstVisibleItem + visibleItemCount >= totalItemCount) {
// End has been reached
// btnaddOutlet.startAnimation(AnimationUtils.loadAnimation(Outlet_List.this,
// android.R.anim.fade_out));
btnDuetoCallCard.setVisibility(View.GONE);
} else {
// btnaddOutlet.startAnimation(AnimationUtils.loadAnimation(Outlet_List.this,
// android.R.anim.fade_in));
btnDuetoCallCard.setVisibility(View.VISIBLE);
}
if (visibleItemCount == totalItemCount)
btnDuetoCallCard.setVisibility(View.VISIBLE);
}
});
}
void populateArray() {
dueadapter = new BaseAdapter() {
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// if (convertView == null) {
convertView = inflater.inflate(R.layout.dueamounts_list_item,
null);
// }
TextView orderNo = (TextView) convertView
.findViewById(R.id.tvdueOrderNo);
TextView orderDate = (TextView) convertView
.findViewById(R.id.tvdueDate);
orderDueAmmount = (TextView) convertView
.findViewById(R.id.tvRemainingDueAmmount);
ImageButton imgbtn = (ImageButton) convertView
.findViewById(R.id.dueImageButton);
orderNo.setText("Order "
+ dueArray.get(position).getOrder_id().getId());
orderDate.setText(dueArray.get(position).getDate());
Double dueAmount = dueArray.get(position).getAmount();
orderDueAmmount.setText(formatDoubleValues(dueAmount));
// old way
// orderNo.setText("" + dueArray.get(position).getOrder());
// orderDate.setText(dueArray.get(position).getDate());
// orderAmmount.setText(dueArray.get(position).getAmmount());
header = (ViewGroup) convertView.findViewById(R.id.header);
header.setId(position);
header.setOnClickListener(due_header_clicked);
ViewGroup body = (ViewGroup) convertView
.findViewById(R.id.body);
View Headerparent = (View) header.getParent();
View image = findViewById(R.id.dueImageButton);
View TAB_Orderdetail = body.findViewById(R.id.btnOrderDetails);
View TAB_Duedetail = body.findViewById(R.id.btnDueDetails);
TAB_Orderdetail.setOnClickListener(change_fragment_listener);
TAB_Duedetail.setOnClickListener(change_fragment_listener);
// imgbtn.setOnClickListener(due_header_clicked);
View placeHolder = convertView
.findViewById(R.id.duefragment_placeholder);
int id = 10000 + position;
placeHolder.setId(id);
dueArray.get(position).setPlaceHolder(id);
Payment item = dueArray.get(position);
if (stateStore.equals("" + position)) {
// header.performClick();
body.setVisibility(View.VISIBLE);
header.performClick();
} else {
body.setVisibility(View.GONE);
}
// totalCollectedDue = (TextView) convertView
// .findViewById(R.id.tvTotalCollectedDueAmount);
return convertView;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return dueArray.get(position);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return dueArray.size();
}
};
Duelist.setAdapter(dueadapter);
dueadapter.notifyDataSetChanged();
Duelist.setDivider(null);
Duelist.setDividerHeight(0);
}
int headerIndex = 0;
// View headerView;
int placeHolder_id = 0;
public OnClickListener due_header_clicked = new OnClickListener() {
#Override
public void onClick(View v) {
onHeaderClicked(v);
clickedHeaderView = v;
}
};
public void onHeaderClicked(View v) {
index = v.getId();
headerIndex = index;
// fr = dueArray.get(index).getDueFragment();
Bundle bundle = new Bundle();
bundle.putInt("index", headerIndex);
fr = tempdueArray.get(index).getDueFragment(headerIndex);
// fr.setArguments(bundle);
// tempdueArray.get(index).setDue_fragment(headerIndex);
Due.this.placeHolder_id = dueArray.get(index).getPlaceHolder();
final Payment item = dueArray.get(index);
// saving the header clicked position for later use
stateStore = "" + v.getId();
View view = (View) v.getParent();
TextView headerDueamount = (TextView) view
.findViewById(R.id.tvRemainingDueAmmount);
headerView = headerDueamount;
DueDetailsRight = (TextView) view.findViewById(R.id.tvduedetialright);
DueDetailsTop = (TextView) view.findViewById(R.id.tvdeudetailstop);
DueDetailsBottom = (TextView) view
.findViewById(R.id.tvdeudetailsBottom1);
DueDetailsrightHorizontal = (TextView) view
.findViewById(R.id.tvDuedetailslefthorizontal);
OrderDetailsBottom = (TextView) view
.findViewById(R.id.tvorderdetailBottom);
OrderDetailstop = (TextView) view.findViewById(R.id.tvorderdetailtop);
OrderDetailsleft = (TextView) view
.findViewById(R.id.tvOrderdetailsleft);
OrderDetailsleftHorizontal = (TextView) view
.findViewById(R.id.tvDuedetailsrighthorizontal);
final View body = view.findViewById(R.id.body);
View image = view.findViewById(R.id.dueImageButton);
View TAB_Orderdetail = body.findViewById(R.id.btnOrderDetails);
View TAB_Duedetail = body.findViewById(R.id.btnDueDetails);
TAB_Orderdetail.setOnClickListener(change_fragment_listener);
TAB_Duedetail.setOnClickListener(change_fragment_listener);
if (body.getVisibility() != View.VISIBLE) {
if (tempstore != null) {
tempstore.setVisibility(View.GONE);
imagetempstore
.setBackgroundResource(R.drawable.ic_due_dropdown_icon);
}
tempstore = body;
imagetempstore = image;
body.setVisibility(View.VISIBLE);
// if (fr == null) {
View test = (View) v.getParent().getParent();
DueDetailsButton = (TextView) test
.findViewById(R.id.btnOrderDetails);
OrderDetailsleft.setVisibility(View.INVISIBLE);
OrderDetailstop.setVisibility(View.INVISIBLE);
DueDetailsBottom.setVisibility(View.INVISIBLE);
OrderDetailsleftHorizontal.setVisibility(View.INVISIBLE);
DueDetailsRight.setVisibility(View.VISIBLE);
DueDetailsTop.setVisibility(View.VISIBLE);
OrderDetailsBottom.setVisibility(View.VISIBLE);
DueDetailsrightHorizontal.setVisibility(View.VISIBLE);
fm = getSupportFragmentManager();
fragmentTransaction = fm.beginTransaction();
// fr = dueArray.get(index).getOrderFragment();
// fragmentTransaction.replace(item.getPlaceHolder(), fr);
// fragmentTransaction.commit();
// fr = dueArray.get(index).getDueFragment();
fr = tempdueArray.get(index).getDueFragment(headerIndex);
fm = getSupportFragmentManager();
fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(item.getPlaceHolder(), fr);
fragmentTransaction.commit();
image.setBackgroundResource(R.drawable.ic_expand_icon);
} else {
image.setBackgroundResource(R.drawable.ic_due_dropdown_icon);
body.setVisibility(View.GONE);
}
}
public OnClickListener change_fragment_listener = new OnClickListener() {
#Override
public void onClick(View v) {
changeFargment(v);
}
};
public void changeFargment(View v) {
View test = (View) v.getParent().getParent();
DueDetailsRight = (TextView) test.findViewById(R.id.tvduedetialright);
DueDetailsTop = (TextView) test.findViewById(R.id.tvdeudetailstop);
DueDetailsBottom = (TextView) test
.findViewById(R.id.tvdeudetailsBottom1);
DueDetailsrightHorizontal = (TextView) test
.findViewById(R.id.tvDuedetailslefthorizontal);
OrderDetailsBottom = (TextView) test
.findViewById(R.id.tvorderdetailBottom);
OrderDetailstop = (TextView) test.findViewById(R.id.tvorderdetailtop);
OrderDetailsleft = (TextView) test
.findViewById(R.id.tvOrderdetailsleft);
OrderDetailsleftHorizontal = (TextView) test
.findViewById(R.id.tvDuedetailsrighthorizontal);
DueDetailsButton = (TextView) test.findViewById(R.id.btnDueDetails);
OrderDetailsButton = (TextView) test.findViewById(R.id.btnOrderDetails);
OrderDetailsButton = (TextView) test.findViewById(R.id.btnOrderDetails);
switch (v.getId()) {
case R.id.btnOrderDetails:
DueDetailsButton.setTextColor(Color.parseColor("#8e8f92"));
OrderDetailsButton.setTextColor(Color.parseColor("#050708"));
// Bundle bundle = new Bundle();
// bundle.putInt("index", headerIndex);
// fr = dueArray.get(headerIndex).getOrderFragment();
fr = tempdueArray.get(headerIndex).getOrderFragment(headerIndex);
// fr.setArguments(bundle);
DueDetailsRight.setVisibility(View.INVISIBLE);
DueDetailsTop.setVisibility(View.INVISIBLE);
OrderDetailsBottom.setVisibility(View.INVISIBLE);
DueDetailsrightHorizontal.setVisibility(View.INVISIBLE);
OrderDetailsleft.setVisibility(View.VISIBLE);
OrderDetailstop.setVisibility(View.VISIBLE);
DueDetailsBottom.setVisibility(View.VISIBLE);
OrderDetailsleftHorizontal.setVisibility(View.VISIBLE);
break;
case R.id.btnDueDetails:
OrderDetailsButton.setTextColor(Color.parseColor("#8e8f92"));
DueDetailsButton.setTextColor(Color.parseColor("#050708"));
Bundle bundle = new Bundle();
bundle.putInt("index", headerIndex);
// fr = dueArray.get(headerIndex).getDueFragment();
fr = tempdueArray.get(headerIndex).getDueFragment(headerIndex);
fr.setArguments(bundle);
OrderDetailsleft.setVisibility(View.INVISIBLE);
OrderDetailstop.setVisibility(View.INVISIBLE);
DueDetailsBottom.setVisibility(View.INVISIBLE);
OrderDetailsleftHorizontal.setVisibility(View.INVISIBLE);
DueDetailsRight.setVisibility(View.VISIBLE);
DueDetailsTop.setVisibility(View.VISIBLE);
OrderDetailsBottom.setVisibility(View.VISIBLE);
DueDetailsrightHorizontal.setVisibility(View.VISIBLE);
break;
case R.id.btnCollection:
break;
case R.id.btndueHome:
Intent intent = new Intent(new Intent(Due.this, MainActivity.class));
intent.putExtra("home", true);
startActivity(intent);
break;
}
// DueDetail.total = 0;
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(Due.this.placeHolder_id, fr);
fragmentTransaction.commit();
}
public void buttonClickActions(View v) {
startActivity(new Intent(Due.this, CallCard.class));
finish();
}
#Override
public void onDoneButtonClick(DialogFragment dialog, String outlet,
String outletId) {
tvOutletName.setText(outlet);
outlet_id = outletId;
populateArray();
}
List<Payment> dueList;
public void initArrays() {
dueList = Entity.query(Payment.class).executeMulti();
// initializing the arraylist with object values
for (int i = 0; i < dueList.size(); i++) {
dueArray.add(dueList.get(i));
DueItem dt = new DueItem();
// dt.setOrder("order " + dueList.get(i).getOrder_id());
// dt.setDate("21July,2015" + dueList.get(i).getDate());
// dt.setAmmount("BDT" + dueList.get(i).getAmount());
tempdueArray.add(dt);
}
}
public String formatDoubleValues(Double myDouble) {
DecimalFormat myFormat = new DecimalFormat("0.00");
return myFormat.format(myDouble);
}
}
And the following class is one of the fragment class that is updating the fragment ListView and the parent Listview it is in.
public class DueDetail extends Fragment {
BaseAdapter dueDetailAdapter;
ListView dueDetailList;
TextView collectionbtn;
TextView totalInitialDue;
CheckBox cbCash, cbCheque;
private String dueAmmount;
double total, totalremainingDue;
int currentDueOnOrder = 100000;
ArrayList<DueCollection> arrayDueDetail = new ArrayList<DueCollection>();
ArrayList<Payment> arrayPayment = new ArrayList<Payment>();
List<DueCollection> duelist;
List<Payment> paymentlist;
private TextView TotalCollectedDue;
Formater fObj = new Formater();
int currentPositon;
int position;
Due dueActivity;
OrderModel om;
DueCollection odi;
boolean setClicked = false;
public DueDetail(int pos) {
//
duelist = Entity.query(DueCollection.class).executeMulti();
for (int i = 0; i < duelist.size(); i++) {
// if (duelist.get(i).getAmount() != null) {
int postion = duelist.get(i).getPayment_id().getId();
if (postion == pos + 1) {
arrayDueDetail.add(duelist.get(i));
}
}
paymentlist = Entity.query(Payment.class).executeMulti();
for (int i = 0; i < paymentlist.size(); i++) {
arrayPayment.add(paymentlist.get(i));
}
// for calculating the total of collected due in the duedetail
// fragment
for (int i = 0; i < arrayDueDetail.size(); i++) {
if (arrayDueDetail.get(i).getAmount() != null) {
int dueAmount = Integer.parseInt(arrayDueDetail.get(i)
.getAmount());
total += dueAmount;
}
}
//
}
#Override
#Nullable
public View onCreateView(LayoutInflater inflater,
#Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.due_amounts_duedetails_history,
container, false);
this.view = view;
dueActivity = (Due) getActivity();
position = dueActivity.getIndex();
DecimalFormat formatter = new DecimalFormat("#,###,###");
totalInitialDue = (TextView) view.findViewById(R.id.tvRemainingDue);
totalInitialDue.setText("BDT "
+ arrayPayment.get(position).getInitialDue());
TotalCollectedDue = (TextView) view
.findViewById(R.id.tvTotalCollectedDueAmount);
String totalduecollection = amountFormatter(total);
TotalCollectedDue.setText("BDT " + totalduecollection);
updateUI();
return view;
}
View view;
public void updateUI() {
if (view == null)
return;
collectionbtn = (TextView) view.findViewById(R.id.btnCollection);
collectionbtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
final Dialog d = new Dialog(getActivity());
d.requestWindowFeature(Window.FEATURE_NO_TITLE);
d.setContentView(R.layout.due_collection_popup);
// d.requestWindowFeature(Window.FEATURE_NO_TITLE);
final EditText et = (EditText) d
.findViewById(R.id.etduecollectionamount);
d.findViewById(R.id.btnCollectionOk).setOnClickListener(
new OnClickListener() {
#Override
public void onClick(View v) {
dueAmmount = et.getText().toString();
if (dueAmmount != null) {
if (!(dueAmmount.equals(""))) {
int incremental_position = position + 1;
// creating a object of duecollection
odi = new DueCollection();
odi.setAmount(dueAmmount);
SimpleDateFormat sdf = new SimpleDateFormat(
"dd MMMM,yyyy");
String currentDate = sdf
.format(new Date());
odi.setDate(currentDate);
Payment payObj = Entity
.query(Payment.class)
.where("_id='"
+ incremental_position
+ "'").execute();
odi.setPayment_id(payObj);
om = Entity
.query(OrderModel.class)
.where("_id='"
+ incremental_position
+ "'").execute();
odi.setOrder_id(om);
odi.save();
arrayDueDetail.add(odi);
// *** duecollection obj creation ends
// here
total = 0;
dueDetailAdapter.notifyDataSetChanged();
for (int i = 0; i < arrayDueDetail
.size(); i++) {
double dueAmount = Integer
.parseInt(arrayDueDetail
.get(i).getAmount());
total += dueAmount;
}
String DueOnOrder = arrayPayment.get(
position).getInitialDue();
double remainingdue = Double
.parseDouble(DueOnOrder)
- total;
dueActivity.dueArray.get(position)
.setAmount(remainingdue);
dueActivity.dueadapter
.notifyDataSetChanged();
payObj.setAmount(remainingdue);
payObj.setSynced("0");
payObj.save();
// set the total remaining due to the
// header textview
String totalduecollection = amountFormatter(total);
TotalCollectedDue.setText("BDT "
+ totalduecollection);
dueActivity.stateStore = "" + position;
setClicked = true;
}
}
d.dismiss();
}
});
d.show();
d.setOnDismissListener(new OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
// dueActivity.populateArray();
Formater fobJ = new Formater();
DueCollectionAsyncTask dcat = new DueCollectionAsyncTask(
dueActivity, "" + odi.getOrder_id().getId(), ""
+ odi.getPayment_id().getOutlet_id()
.getId(), dueAmmount, fobJ
.getDateinPrefferedFormat());
dcat.execute();
}
});
}
});
// dueActivity.header.performClick();
dueDetailList = (ListView) view.findViewById(R.id.listViewDueDetails);
dueDetailAdapter = new BaseAdapter() {
LayoutInflater inflater = (LayoutInflater) getActivity()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// if (convertView == null) {
convertView = inflater.inflate(
R.layout.due_amounts_duedetails_product_items, null);
// }
TextView dueFragproduct = (TextView) convertView
.findViewById(R.id.tvduefragDate);
TextView dueFragDueCollectionAmmount = (TextView) convertView
.findViewById(R.id.tvduefragProductAmmount);
dueFragproduct.setText(arrayDueDetail.get(position).getDate());
DecimalFormat formatter = new DecimalFormat("#,###,###");
String commaformatedstring = ""
+ arrayDueDetail.get(position).getAmount();
dueFragDueCollectionAmmount.setText("BDT "
+ commaformatedstring);
return convertView;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return arrayDueDetail.get(position);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return arrayDueDetail.size();
}
};
dueDetailList.setAdapter(dueDetailAdapter);
dueDetailList.setDivider(null);
dueDetailList.setDividerHeight(0);
setListViewHeightBasedOnChildren(dueDetailList);
}
/****
* Method for Setting the Height of the ListView dynamically. Hack to fix
* the issue of not showing all the items of the ListView when placed inside
* a ScrollView
****/
public void setListViewHeightBasedOnChildren(ListView listView) {
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null)
return;
int desiredWidth = MeasureSpec.makeMeasureSpec(listView.getWidth(),
MeasureSpec.UNSPECIFIED);
int totalHeight = 0;
View view = null;
for (int i = 0; i < listAdapter.getCount(); i++) {
view = listAdapter.getView(i, view, listView);
if (i == 0)
view.setLayoutParams(new ViewGroup.LayoutParams(desiredWidth,
LayoutParams.WRAP_CONTENT));
view.measure(desiredWidth, MeasureSpec.UNSPECIFIED);
totalHeight += view.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight
+ (listView.getDividerHeight() * (listAdapter.getCount() - 1));
listView.setLayoutParams(params);
listView.requestLayout();
}
public void confirmationDialog(String msg, String title, final Dialog d) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
getActivity());
alertDialogBuilder.setMessage(msg);
final AlertDialog alertDialog = alertDialogBuilder.create();
alertDialogBuilder.setTitle(title);
alertDialogBuilder.setPositiveButton("yes",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
d.dismiss();
}
});
alertDialogBuilder.setNegativeButton("No",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
alertDialog.cancel();
}
});
AlertDialog alertDialog2 = alertDialogBuilder.create();
alertDialog2.show();
Button nbutton = alertDialog2
.getButton(DialogInterface.BUTTON_NEGATIVE);
nbutton.setBackgroundColor(Color.parseColor("#47b96b"));
Button pbutton = alertDialog2
.getButton(DialogInterface.BUTTON_POSITIVE);
pbutton.setBackgroundColor(Color.parseColor("#e06165"));
int textViewId = alertDialog2.getContext().getResources()
.getIdentifier("android:id/alertTitle", null, null);
TextView tv = (TextView) alertDialog2.findViewById(textViewId);
tv.setTextColor(getResources().getColor(R.color.coral_blue));
}
public String amountFormatter(double number) {
DecimalFormat formatter = new DecimalFormat("#,###,###");
String totalduecollection = formatter.format(Double.parseDouble(""
+ number));
return totalduecollection;
}
}
The button displays a dialog through which ListView inside the fragment gets populated.
not exactly clear to me. Did you meant inside your dialog you have some action that reflects on the fragment lisview?
have to click the parent list view item again to see the fragment and its content. I want the Fragment view and its updated content remain viewed after the dialog is dismissed
What i understand here u are doing something inside child view fragment that reflects on parent view list item, you are expecting the parent item data to be updated in view and also keeping the view state here u meant to be opened the parent item as it was (when u are updating the something inside fragment or dialog whatever)
My primary answer is you keep somehow keep the position to a member reference of the activity class where you actually setting the parent list in parent item onClick callback.
keep this position and later what you have to is to call a method inside adapter to pass the position to set a perform clic on item view
you may get a hints from this link..
http://blog.wittchen.biz.pl/how-to-highlight-and-click-on-listview-item-in-android-programmatically/
I have three fragments, the second and the third one, have a listView in their respective layout.
initially, the listView of both "second and third Frament", is populated with the same items. i other words, initially the the listView of
the second fragment and the third one, contain the following where CB: is checkBox and IV: is ImageView and t is: textview, and SaveButton is a buton
t1........CB.......IV
t2........CB.......IV
t3........CB.......IV
t4........CB.......IV
t5........CB.......IV
t6........CB.......IV
SaveButton
what i am trying to do is, while i am in the second fragment and selected an item(s) from the listView "using the checkbox" and clicked "Save" button, then, that item i selected, should be deleted from the listView in the third Fragment.
to achieve this,in getview(), i checked if the the checkBox is checked from the the listView of the second fragment, and if it is checked, i add the checked items
to a list. as shown in getView():
Second Fragment:
private void setUpListView() {
// TODO Auto-generated method stub
this.topicsList = new ArrayList<String>();
for (int i = 0; i < this.topics.length; i++) {
this.topicsList.add(topics[i]);
}
this.adapter = new ListViewAdapter(getActivity(), this.topicsList, ECO_FRAG_ID);
this.listView.setAdapter(adapter);
}
Third Fragment:
private void setUpListView() {
// TODO Auto-generated method stub
this.topicsList = new ArrayList<String>();
for (int i = 0; i < this.topics.length; i++) {
this.topicsList.add(topics[i]);
}
this.adapter = new ListViewAdapter(getActivity(), this.topicsList, LOGGER_FRAG_ID);
this.listView.setAdapter(adapter);
}
BaseAdapter:
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
if (convertView == null) {
LayoutInflater layoutinflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = layoutinflater.inflate(R.layout.list_items_layout, null);
}
if (this.checkedItemsList1 == null) {
this.checkedItemsList1 = new ArrayList<String>();
}
if (this.checkedItemsList2 == null) {
this.checkedItemsList2 = new ArrayList<String>();
}
final TextView tv = (TextView) convertView.findViewById(R.id.tvlist_topic);
final CheckBox cb = (CheckBox) convertView.findViewById(R.id.cbList_hook);
final ImageView iv = (ImageView) convertView.findViewById(R.id.ivList_delete);
tv.setText(this.topicsList.get(position));
if (cb.isChecked() && (this.id == 1) ) {
this.checkedItemsList1.add(this.topicsList.get(position));
this.setCheckedItemsList1(this.checkedItemsList1);
}
if (cb.isChecked() && (this.id == 2) ) {
this.checkedItemsList2.add(this.topicsList.get(position));
this.setCheckedItemsList2(this.checkedItemsList2);
}
iv.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (cb.isChecked())
cb.setChecked(false);
topicsList.remove(position);
notifyDataSetChanged();
}
});
return convertView;
}
And i created an interface, which is initialised in onAttach() and called when i click the savebuton in the secondFragment as folows:
private OnClickListener btnSaveListener = new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getActivity(), "Save to SQLite", Toast.LENGTH_SHORT).show();
Log.d(TAG, "size: " + adapter.getCheckedItemsList1().size());
iCSC.onCheckedStateChanged(adapter.checkedItemsList1, ECO_FRAG_ID);
}
};
this inerface, the mainActivity implements it, and in the implemntation of the interface, i pass the list f the checked items from the second Fragment to the third
Fragment through a public method in the third fragmet that updates the list and then assign the list to the adapter, as follows:
#Override
public void onCheckedStateChanged(ArrayList<String> list, int id) {
// TODO Auto-generated method stub
switch (id) {
case 1:
((Logger_Settings_Frag) this.fragList.get(2)).updateTopicList(list);
break;
case 2:
break;
}
}
**updateTopicList in the third fragment**
public void updateTopicList(ArrayList<String> list) {
for (String str : list) {
this.topicsList.remove(str);
}
this.adapter = new ListViewAdapter(getActivity(), this.topicsList, LOGGER_FRAG_ID);
this.listView.setAdapter(adapter);
}
updateTopicList in the third fragment
public void updateTopicList(ArrayList<String> list) {
for (String str : list) {
this.topicsList.remove(str);
}
this.adapter = new ListViewAdapter(getActivity(), this.topicsList, LOGGER_FRAG_ID);
this.listView.setAdapter(adapter);
}
when i run that code, in the saveButton listener of the second fragment, the log.d message displays that the size of the list that should contain the items that was checked, is zero size?!
please have a look at the code and let me know what i am missing?
try this: Its a sample Project OneActivity with two Fragments:
public ArrayList myBeansList_frgnt1;
public ArrayList myBeansList_frgnt2;
by clicking the save button iterate the myBeansList_frgnt1 and checking the condition that any item is selected or not. if item is selected i am adding that item to myBeansList_frgnt2 .showing in fragment2.
MainActivity:
public class MainActivity extends FragmentActivity {
private FragmentManager mFragmentManager;
private MyFragment1 myFragment1;
public ArrayList<MyBean> myBeansList_frgnt1;
public ArrayList<MyBean> myBeansList_frgnt2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mFragmentManager = getSupportFragmentManager();
myBeansList_frgnt1 = new ArrayList<MyBean>();
myBeansList_frgnt2 = new ArrayList<MyBean>();
}
#Override
protected void onResume() {
super.onResume();
myFragment1 = new MyFragment1();
FragmentTransaction mTransaction = mFragmentManager.beginTransaction();
mTransaction.replace(R.id.framid, myFragment1, "applock").commit();
}
}
MyBaseAdpter: maintaining the states in the MyBean object
#Override
public View getView(int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = LayoutInflater.from(mContext).inflate(R.layout.list_item, null);
holder.mTextView = (TextView) view.findViewById(R.id.textView1);
holder.mBox = (CheckBox) view.findViewById(R.id.checkBox1);
holder.mImageView = (ImageView) view.findViewById(R.id.imageView1);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
final MyBean mBean = mBeansList.get(position);
holder.mBox.setOnCheckedChangeListener(null);
holder.mBox.setChecked(mBean.isChecked());
holder.mBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
mBean.setChecked(true);
} else {
mBean.setChecked(false);
}
}
});
// setting text and image
holder.mTextView.setText(mBean.getmName());
holder.mImageView.setImageResource(mBean.getmImgId());
return view;
}
private class ViewHolder {
TextView mTextView;
CheckBox mBox;
ImageView mImageView;
}
Fragment1:
public class MyFragment1 extends Fragment {
private ListView mListView;
private MyBaseAdpter myBaseAdpter;
private Button mButton;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_layout, null);
mListView = (ListView) view.findViewById(R.id.listviewid);
mButton = (Button) view.findViewById(R.id.bttnid);
return view;
}
#Override
public void onResume() {
super.onResume();
final MainActivity mActivity = (MainActivity) getActivity();
myBaseAdpter = new MyBaseAdpter(mActivity.myBeansList_frgnt1, getActivity());
mListView.setAdapter(myBaseAdpter);
mButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int size = mActivity.myBeansList_frgnt1.size();
for (int i = 0; i < size; i++) {
MyBean mMyBean = mActivity.myBeansList_frgnt1.get(i);
if (mMyBean.isChecked()) {
mActivity.myBeansList_frgnt2.add(mMyBean);
}
}
}
});
}
}
Fragment2:
public class MyFragment2 extends Fragment {
private ListView mListView;
private MyBaseAdpter myBaseAdpter;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_layout, null);
mListView = (ListView) view.findViewById(R.id.listviewid);
return view;
}
#Override
public void onResume() {
super.onResume();
MainActivity mActivity = (MainActivity) getActivity();
myBaseAdpter = new MyBaseAdpter(mActivity.myBeansList_frgnt2, getActivity());
mListView.setAdapter(myBaseAdpter);
}
}
MyBean:
public class MyBean {
private String mName;
private int mImgId;
private boolean isChecked;
public String getmName() {
return mName;
}
public void setmName(String mName) {
this.mName = mName;
}
public int getmImgId() {
return mImgId;
}
public void setmImgId(int mImgId) {
this.mImgId = mImgId;
}
public boolean isChecked() {
return isChecked;
}
public void setChecked(boolean isChecked) {
this.isChecked = isChecked;
}
public MyBean() {
super();
// TODO Auto-generated constructor stub
}
}
I am trying to getting the total Count of the getView custom listview. But want to display in the different layout. Here is my onCreatedView. I am not sure how to inflate the layout. Thanks for all your help.
private static ListView addDropListView = null;
private TransactionAddDropAdapter addDropAdapter = null;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
fragmentPendingTrades = inflater.inflate(R.layout.fragment_transactions_pending, container, false);
pendingTradesView = inflater;
return fragmentPendingTrades;
}
public void onViewCreated(final View view, final Bundle savedInstanceState) {
this.addDropListView = (ListView) view.findViewById(R.id.transactions_pending_transactionsListView);
this.addDropAdapter = new TransactionAddDropAdapter(pendingTradesView);
this.addDropListView.setAdapter(this.addDropAdapter);
this.emptyTransationsContainer = view.findViewById(R.id.transactions_pending_transactions_emptyContainer);
TextView getTotalCount = (TextView) view.findViewById(R.id.transactions_pending_TransactionsAddDropCount);
getTotalCount.setText(""+addDropListView.getCount());
}
Here is my Holderview that get the getView
public class TransactionAddDropAdapter extends BaseAdapter {
private LayoutInflater inflater = null;
private List<TransactionAddDrop> addDropList = new ArrayList<TransactionAddDrop>();
public TransactionAddDropAdapter(LayoutInflater inflater) {
this.inflater = inflater;
}
public void setAddDropList(List<TransactionAddDrop> addDropList) {
clearAddDropList();
for (TransactionAddDrop ad : addDropList) {
if (ad.isStateApprove()) {
this.addDropApprovalsList.add(ad);
} else {
this.addDropList.add(ad);
}
}
}
public void clearAddDropList() {
this.addDropList.clear();
this.addDropApprovalsList.clear();
}
#Override
public int getCount() {
int size = this.addDropList.size();
if (this.addDropApprovalsList.size() > 0) {
size += 1;
}
return size;
}
#Override
public Object getItem(int position) {
try {
if (this.addDropList == null) {
return null;
} else if (position < addDropList.size()) {
return this.addDropList.get(position);
} else {
return this.addDropApprovalsList;
}
} catch (Exception e) {
return null;
}
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
final TransactionAddDrop addDropData = this.addDropList.get(position);
TransactionAddDropViewHolder holder = null;
if (convertView == null) {
convertView = inflater.inflate(R.layout.fragment_pending_transaction_list_item, null);
holder = new TransactionAddDropViewHolder();
holder.withdrawButton = convertView.findViewById(R.id.pendingTransactionItem_withdrawButton);
holder.addContainer = (LinearLayout) convertView.findViewById(R.id.pendingTransactionItem_addContainer);
holder.dropContainer = (LinearLayout) convertView.findViewById(R.id.pendingTransactionItem_dropContainer);
holder.rootView = convertView.findViewById(R.id.swipeRight);
holder.swipeButtons();
convertView.setTag(holder);
} else {
holder = (TransactionAddDropViewHolder) convertView.getTag();
holder.swipeButtons();
}
}
Ok, I "think" I know what's going on here. You setup your ListView and add its TransactionAddDropAdapter, and then set the total amount of items.
this.addDropListView = (ListView) view.findViewById(R.id.transactions_pending_transactionsListView);
this.addDropAdapter = new TransactionAddDropAdapter(pendingTradesView);
this.addDropListView.setAdapter(this.addDropAdapter);
TextView getTotalCount = (TextView) view.findViewById(R.id.transactions_pending_TransactionsAddDropCount);
getTotalCount.setText(""+addDropListView.getCount());
However, at this point, you haven't called setAddDropList(List<TransactionAddDrop> addDropList) on addDropAdapter, so addDropList in getCount() is still an empty array, so getCount() == 0, which is why you are seeing 0 being displayed.
So, you need to find where you call addDropAdapter.setAddDropList() and then call getTotalCount.setText(""+addDropListView.getCount()); right after in order to update the total number of rows.