Android Listview autoscroll makes items invisible - java

I have progress listview of progress items. Whenever the item is finished I checkmark it.
This Progress items are divided into Phases. Each phase can contain Steps. After all steps are done and marked with checkmark, code marks whole phase as done.
At the end what I do is just render a listview of phases and for each phase I dynamicly add another listview in it. I end up with listview with more listviews in it.
This works fine and I don't have any problems with it.
My boss asked me to create auto scroller which would follow the steps as being completed. This I implemented and was happy to see that It works.
Problem: I was happy that It works only to the point when the something little over of half is reached. Then suddenly items disapear. When I touch the list, List goes back to top and all the items are visible.
Any idea what could couse this behavior?
The code for this is quite large so I will share only the parts I think are needed.
//Adapters
public class ProcessFeedbackAdapter extends android.widget.BaseAdapter {
public static final String TAG = "ProcessFeedbackAdapter";
public Context appContext;
public ProgressOverviewData ProgressOverviewData;
public ListView Listview;
public int FirstNotCompletedIndex=0;
public void UpdateList(){
HotApplication.getHandler().post(new Runnable(){
#Override
public void run() {
notifyDataSetChanged();
}
});
}
public ProcessFeedbackAdapter(Context Context,ProgressOverviewData ProgressOverviewData,ListView listview){
this.appContext=Context;
this.ProgressOverviewData=ProgressOverviewData;
this.Listview=listview;
}
#Override
public int getCount() {
return ProgressOverviewData.Phases.size();
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
public void ScrollToCurrentlyActiveTask(int y){
int listviewBottom = Listview.getBottom();
if(listviewBottom <y*50){
Listview.scrollTo(0, listviewBottom);
}
else {
Listview.scrollTo(0,y*50);
}
Listview.computeScroll();
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
try {
Phase curItem = ProgressOverviewData.Phases.get(i);
LayoutInflater inflater = (LayoutInflater) appContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.progress_list_item, null);
ListView ChildList=view.findViewById(R.id.childrenList);
ViewGroup.LayoutParams params = ChildList.getLayoutParams();
int ListHeight=curItem.PhaseSteps.size()*50;
params.height=ListHeight;
ChildList.setLayoutParams(params);
TextView ProgressMessage = (TextView) view.findViewById(R.id.ProgressMessage);
ImageView Check = (ImageView) view.findViewById(R.id.CheckMark);
ImageView ErrorMark = (ImageView) view.findViewById(R.id.ErrorMark);
ProcessFeedbackChildrenAdapter ChilAdapter=new ProcessFeedbackChildrenAdapter(appContext,curItem.PhaseSteps);
ChildList.setAdapter(ChilAdapter);
int CheckVisibility = 0;
int ErrorVisibility=0;
if(curItem.Status.equals(AppEnums.StepResult.NotCompleted)){
CheckVisibility=View.INVISIBLE;
ErrorVisibility=View.INVISIBLE;
}
else if(curItem.Status.equals(AppEnums.StepResult.Completed)){
CheckVisibility=View.VISIBLE;
ErrorVisibility=View.INVISIBLE;
}
else if(curItem.Status.equals(AppEnums.StepResult.Failed)){
ErrorVisibility=View.VISIBLE;
CheckVisibility=View.INVISIBLE;
}
Check.setVisibility(CheckVisibility);
ErrorMark.setVisibility(ErrorVisibility);
ProgressMessage.setText(curItem.PhaseName);
return view;
} catch (Exception e) {
System.out.println("Something went wrong.");
}
return view;
}
}
class ProcessFeedbackChildrenAdapter extends android.widget.BaseAdapter {
public static final String TAG = "ProcessFeedbackChildrenAdapter";
public Context appContext;
public ArrayList<Step> Steps= new ArrayList<Step>();
public void UpdateList(){
HotApplication.getHandler().post(new Runnable(){
#Override
public void run() {
notifyDataSetChanged();
}
});
}
public ProcessFeedbackChildrenAdapter(Context Context,ArrayList<Step> Steps){
this.appContext=Context;
this.Steps=Steps;
}
#Override
public int getCount() {
return Steps.size();
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
try {
LayoutInflater inflater = (LayoutInflater) appContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.progress_list_item_children, null);
TextView ProgressMessage = (TextView) view.findViewById(R.id.ProgressMessage);
ImageView Check = (ImageView) view.findViewById(R.id.CheckMark);
ImageView ErrorMark = (ImageView) view.findViewById(R.id.ErrorMark);
Step curItem = Steps.get(i);
int CheckVisibility = 0;
int ErrorVisibility=0;
if(curItem.Status== AppEnums.StepResult.NotCompleted){
CheckVisibility=View.INVISIBLE;
ErrorVisibility=View.INVISIBLE;
}else {
if(curItem.Status== AppEnums.StepResult.Completed){
CheckVisibility=View.VISIBLE;
ErrorVisibility=View.INVISIBLE;
}
else if(curItem.Status==AppEnums.StepResult.Failed){
ErrorVisibility=View.VISIBLE;
CheckVisibility=View.INVISIBLE;
}
}
ProgressMessage.setText(curItem.StepName);
Check.setVisibility(CheckVisibility);
ErrorMark.setVisibility(ErrorVisibility);
return view;
} catch (Exception e) {
System.out.println("Something went wrong.");
}
return view;
}
}
// Main list view
<ListView
android:id="#+id/ProgressStepsContainer"
android:layout_width="0dp"
android:layout_height="267dp"
android:fastScrollEnabled="false"
android:scrollbarThumbVertical="#drawable/scrollbar_vertical_thumb"
android:verticalScrollbarPosition="left"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="#+id/ProgressErrorContainer"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/ProgressMessage">
</ListView>
// Phases list item
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="0dp">
<ImageView
android:id="#+id/CheckMark"
android:layout_width="50dp"
android:layout_height="50dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/ic_overview_check" />
<ImageView
android:id="#+id/ErrorMark"
android:layout_width="50dp"
android:layout_height="50dp"
android:visibility="visible"
app:layout_constraintStart_toStartOf="#+id/CheckMark"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/ic_overview_error" />
<TextView
android:id="#+id/ProgressMessage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="TextView"
android:textAlignment="center"
android:textColor="#color/colorWhitish"
android:textSize="18sp"
app:layout_constraintBottom_toBottomOf="#+id/CheckMark"
app:layout_constraintStart_toEndOf="#+id/CheckMark"
app:layout_constraintTop_toTopOf="parent" />
<ListView
android:id="#+id/childrenList"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
app:layout_constraintStart_toEndOf="#+id/CheckMark"
app:layout_constraintTop_toBottomOf="#+id/ProgressMessage" />
</androidx.constraintlayout.widget.ConstraintLayout>
// Steps (inner) list item
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="50dp">
<ImageView
android:id="#+id/CheckMark"
android:layout_width="50dp"
android:layout_height="50dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/ic_overview_check" />
<ImageView
android:id="#+id/ErrorMark"
android:layout_width="50dp"
android:layout_height="50dp"
android:visibility="visible"
app:layout_constraintStart_toStartOf="#+id/CheckMark"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/ic_overview_error" />
<TextView
android:id="#+id/ProgressMessage"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:gravity="center"
android:text="TextView"
android:textAlignment="center"
android:textColor="#color/colorWhitish"
android:textSize="18sp"
app:layout_constraintBottom_toBottomOf="#+id/CheckMark"
app:layout_constraintStart_toEndOf="#+id/CheckMark"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

Your adapter code does not work in my phone. Only part of the child list is shown. In addition, I think your requirements are easier to implement by ExpandableListView. Therefore I followed your data structure and created the following demo codes which use ExpandableListView. You can start a new project and try it.
MainActivity.java:
public class MainActivity extends AppCompatActivity {
ProgressOverviewData sampleData;
ProcessFeedbackAdapter1 adapter;
ExpandableListView listView;
TextView textView;
int completedPhase = 0;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sampleData = new ProgressOverviewData("Project", new ArrayList<Phase>());
textView = findViewById(R.id.ProgressMessage);
textView.setText(sampleData.projectName);
listView = findViewById(R.id.ProgressStepsContainer);
adapter = new ProcessFeedbackAdapter1(this, sampleData);
listView.setAdapter(adapter);
// Disable ExpandableListView from group collapse by override OnGroupClickListener.
listView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView expandableListView, View view, int i, long l) {
return true;
}
});
for (int i = 0; i < sampleData.Phases.size(); i++) listView.expandGroup(i);
Button btAddPhase = findViewById(R.id.bt_add_phase);
btAddPhase.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Phase newPhase = genNewPhase();
sampleData.Phases.add(newPhase);
adapter.notifyDataSetChanged();
listView.expandGroup(sampleData.Phases.size() - 1);
textView.setText(sampleData.projectName + " [" + completedPhase + "/" + sampleData.Phases.size() + "]");
}
});
Button btCompletedStep = findViewById(R.id.bt_completed_step);
btCompletedStep.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
boolean stepCompleted = false;
Step step;
String msg = "";
int viewPosition = 0;
for (int i = 0; i < adapter.getGroupCount(); i++) {
viewPosition++;
for (int j = 0; j < adapter.getChildrenCount(i); j++) {
viewPosition++;
if (adapter.getChild(i, j).Status == AppEnums.StepResult.NotCompleted) {
step = adapter.getChild(i, j);
step.Status = AppEnums.StepResult.Completed;
msg = step.StepName + " Completed!";
if (j == adapter.getGroup(i).PhaseSteps.size() - 1) {
adapter.getGroup(i).Status = AppEnums.StepResult.Completed;
completedPhase++;
textView.setText(sampleData.projectName + " [" + completedPhase + "/" + sampleData.Phases.size() + "]");
msg += "\n" + adapter.getGroup(i).PhaseName + " Completed!!!!!";
}
stepCompleted = true;
break;
}
}
if (stepCompleted) break;
}
if (stepCompleted) {
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "All Completed", Toast.LENGTH_LONG).show();
}
listView.smoothScrollToPositionFromTop(viewPosition - 1, 0);
adapter.notifyDataSetChanged();
}
});
}
private Phase genNewPhase() {
int phaseId = sampleData.Phases.size() + 1;
Random random = new Random();
int numberOfSteps = random.nextInt(5) + 1;
ArrayList<Step> steps = new ArrayList<>();
for (int j = 0; j < numberOfSteps; j++) {
Step step = new Step("Step " + (phaseId) + "-" + (j + 1));
steps.add(step);
}
return new Phase("Phase " + (phaseId) + " [" + steps.size() + "]", steps);
}
}
ProcessFeedbackAdapter1.java:
public class ProcessFeedbackAdapter1 extends BaseExpandableListAdapter {
public static final String TAG = "ProcessFeedbackAdapter";
public Context appContext;
public ProgressOverviewData ProgressOverviewData;
public ProcessFeedbackAdapter1(Context Context, ProgressOverviewData ProgressOverviewData) {
this.appContext = Context;
this.ProgressOverviewData = ProgressOverviewData;
}
#Override
public int getGroupCount() {
return ProgressOverviewData.Phases.size();
}
#Override
public int getChildrenCount(int i) {
return ProgressOverviewData.Phases.get(i).PhaseSteps.size();
}
#Override
public Phase getGroup(int i) {
return ProgressOverviewData.Phases.get(i);
}
#Override
public Step getChild(int i, int i1) {
return ProgressOverviewData.Phases.get(i).PhaseSteps.get(i1);
}
#Override
public long getGroupId(int i) {
return 0;
}
#Override
public long getChildId(int i, int i1) {
return 0;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public View getGroupView(int i, boolean b, View view, ViewGroup viewGroup) {
try {
Phase curItem = getGroup(i);
LayoutInflater inflater = (LayoutInflater) appContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.progress_list_item, null);
TextView ProgressMessage = view.findViewById(R.id.ProgressMessage);
ImageView Check = view.findViewById(R.id.CheckMark);
ImageView ErrorMark = view.findViewById(R.id.ErrorMark);
int CheckVisibility = 0;
int ErrorVisibility = 0;
if (curItem.Status.equals(AppEnums.StepResult.NotCompleted)) {
CheckVisibility = View.INVISIBLE;
ErrorVisibility = View.INVISIBLE;
} else if (curItem.Status.equals(AppEnums.StepResult.Completed)) {
CheckVisibility = View.VISIBLE;
ErrorVisibility = View.INVISIBLE;
} else if (curItem.Status.equals(AppEnums.StepResult.Failed)) {
ErrorVisibility = View.VISIBLE;
CheckVisibility = View.INVISIBLE;
}
Check.setVisibility(CheckVisibility);
ErrorMark.setVisibility(ErrorVisibility);
ProgressMessage.setText(curItem.PhaseName);
} catch (Exception e) {
System.out.println("Something went wrong.");
}
return view;
}
#Override
public View getChildView(int i, int i1, boolean b, View view, ViewGroup viewGroup) {
try {
LayoutInflater inflater = (LayoutInflater) appContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.progress_list_item_children, null);
TextView ProgressMessage = view.findViewById(R.id.ProgressMessage);
ImageView Check = view.findViewById(R.id.CheckMark);
ImageView ErrorMark = view.findViewById(R.id.ErrorMark);
Step curItem = getChild(i, i1);
int CheckVisibility = 0;
int ErrorVisibility = 0;
if (curItem.Status == AppEnums.StepResult.NotCompleted) {
CheckVisibility = View.INVISIBLE;
ErrorVisibility = View.INVISIBLE;
} else {
if (curItem.Status == AppEnums.StepResult.Completed) {
CheckVisibility = View.VISIBLE;
ErrorVisibility = View.INVISIBLE;
} else if (curItem.Status == AppEnums.StepResult.Failed) {
ErrorVisibility = View.VISIBLE;
CheckVisibility = View.INVISIBLE;
}
}
ProgressMessage.setText(curItem.StepName);
Check.setVisibility(CheckVisibility);
ErrorMark.setVisibility(ErrorVisibility);
} catch (Exception e) {
System.out.println("Something went wrong.");
}
return view;
}
#Override
public boolean isChildSelectable(int i, int i1) {
return false;
}
}
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000000"
tools:context=".MainActivity">
<TextView
android:id="#+id/ProgressMessage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Progress Messages:"
android:textColor="#F8F8F8"
android:textSize="20sp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/bt_add_phase"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingStart="20dp"
android:text="Add Phase"
app:layout_constraintRight_toLeftOf="#id/bt_completed_step"
app:layout_constraintTop_toTopOf="parent"
tools:ignore="RtlSymmetry" />
<Button
android:id="#+id/bt_completed_step"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingStart="20dp"
android:text="Completed Step"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:ignore="RtlSymmetry" />
<ImageView
android:id="#+id/ProgressErrorContainer"
android:layout_width="50dp"
android:layout_height="50dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="#+id/ProgressMessage" />
<ExpandableListView
android:id="#+id/ProgressStepsContainer"
android:layout_width="0dp"
android:layout_height="267dp"
android:background="#000033"
android:fastScrollEnabled="false"
android:verticalScrollbarPosition="left"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="#+id/ProgressErrorContainer"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/ProgressMessage" />
</androidx.constraintlayout.widget.ConstraintLayout>
progress_list_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="0dp">
<ImageView
android:id="#+id/CheckMark"
android:layout_width="50dp"
android:layout_height="50dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#android:drawable/checkbox_on_background" />
<ImageView
android:id="#+id/ErrorMark"
android:layout_width="50dp"
android:layout_height="50dp"
android:visibility="visible"
app:layout_constraintStart_toStartOf="#+id/CheckMark"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#android:drawable/ic_delete" />
<TextView
android:id="#+id/ProgressMessage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:textAlignment="center"
android:textColor="#F8F8F8"
android:textSize="18sp"
app:layout_constraintBottom_toBottomOf="#+id/CheckMark"
app:layout_constraintStart_toEndOf="#+id/CheckMark"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
progress_list_item_children.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:paddingStart="50dp"
android:layout_width="wrap_content"
android:layout_height="50dp">
<ImageView
android:id="#+id/CheckMark"
android:layout_width="50dp"
android:layout_height="50dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#android:drawable/checkbox_on_background" />
<ImageView
android:id="#+id/ErrorMark"
android:layout_width="50dp"
android:layout_height="50dp"
android:visibility="visible"
app:layout_constraintStart_toStartOf="#+id/CheckMark"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#android:drawable/ic_delete" />
<TextView
android:id="#+id/ProgressMessage"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:gravity="center"
android:textAlignment="center"
android:textColor="#F8F8F8"
android:textSize="18sp"
app:layout_constraintBottom_toBottomOf="#+id/CheckMark"
app:layout_constraintStart_toEndOf="#+id/CheckMark"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
For the classes that related to your data structure, you can copy from your original project.

Related

ViewPager inside Dialog not showing

I have a custom dialog that has a ViewPager inside of it, when the dialog shows the ViewPager is just blank, not progressing on swipe or when pressing the "Next" button I implemented. I tried slightly altering my code and it didn't work. I saw several posts like this, but none of their solutions worked. PS if some things don't make sense or have mismatched names then that's because I renamed/removed some of the files/variables to simplify.
SliderAdapter:
public class SliderAdapter extends PagerAdapter {
private Context context;
private LayoutInflater layoutInflater;
private ArrayList<String> text;
public SliderAdapter(Context context, ArrayList<String> text) {
this.context = context;
this.text = text;
}
public String[] txtH = {
"test1",
"test2",
"test3"
};
#Override
public int getCount() {
return txtH.length;
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object object) {
return view == (ConstraintLayout) object;
}
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup container, int position) {
layoutInflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.slide_layout_wr, container, false);
TextView txt1 = view.findViewById(R.id.txt11);
TextView txt2 = view.findViewById(R.id.txt22);
txt1.setText(txtH[position]);
txt2.setText(text.get(position));
container.addView(view);
return view;
}
#Override
public void destroyItem(#NonNull ViewGroup container, int position, #NonNull Object object) {
container.removeView((ConstraintLayout) object);
}
}
Dialog itself:
public class DialogWeeklyReport extends AppCompatDialogFragment {
...
#NonNull
#Override
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(),
R.style.Dialog);
LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.dialog, null);
preferences = getActivity().getSharedPreferences("label", 0);
Random random = new Random();
text.add("test1");
text.add("test2");
text.add("test3");
viewPager = view.findViewById(R.id.viewPager);
dotLayout = view.findViewById(R.id.dotLayout);
next = view.findViewById(R.id.next);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (next.getText().toString().equals("Proceed")) {
dismiss();
} else {
viewPager.setCurrentItem(currentPage + 1);
}
}
});
back = view.findViewById(R.id.back);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
viewPager.setCurrentItem(currentPage--);
}
});
builder.setView(view)
.setCancelable(true);
addDotsIndicator(0);
viewPager.setOnPageChangeListener(viewListener);
adapter = new SliderAdapter(getActivity(), text);
return builder.create();
}
private void addDotsIndicator(int position) {
dots = new TextView[3];
dotLayout.removeAllViews();
for (int i = 0; i<dots.length; i++) {
dots[i] = new TextView(getActivity());
dots[i].setText(Html.fromHtml("&#8226"));
dots[i].setTextSize(35);
dots[i].setTextColor(Color.parseColor("#404040"));
dotLayout.addView(dots[i]);
}
if(dots.length > 0) {
dots[position].setTextColor(Color.BLACK);
}
if (currentPage == 0) {
back.setEnabled(false);
next.setEnabled(true);
back.setText("");
next.setText("Next");
}
}
ViewPager.OnPageChangeListener viewListener = new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
addDotsIndicator(position);
currentPage = position;
if (currentPage == 0) {
back.setEnabled(false);
next.setEnabled(true);
back.setText("");
next.setText("Next");
} else if (currentPage == 1) {
back.setEnabled(true);
next.setEnabled(true);
back.setText("Back");
next.setText("Next");
} else if (currentPage == 2) {
back.setEnabled(true);
next.setEnabled(false);
back.setText("Back");
next.setText("Proceed");
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
};
}
Dialog XML:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/dialog_bg"
app:cardCornerRadius="20dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<androidx.viewpager.widget.ViewPager
android:id="#+id/viewPager"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<LinearLayout
android:id="#+id/dotLayout"
android:layout_width="wrap_content"
android:layout_height="30dp"
android:layout_centerHorizontal="true"
android:layout_margin="15dp"
android:layout_below="#+id/viewPager"
android:orientation="horizontal" />
<Button
android:id="#+id/back"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:layout_below="#+id/viewPager"
android:background="#android:color/transparent"
android:elevation="0dp"
android:text="Back"
android:textColor="#android:color/black" />
<Button
android:id="#+id/next"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_below="#+id/viewPager"
android:layout_margin="5dp"
android:background="#android:color/transparent"
android:elevation="0dp"
android:text="Next"
android:textColor="#android:color/black" />
</RelativeLayout>
ViewPager's slide layout:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_height="match_parent"
android:background="#android:color/white">
<TextView
android:id="#+id/txt11"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TEST"
android:textColor="#android:color/black"
android:textSize="30sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.24000001" />
<TextView
android:id="#+id/txt22"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Test"
android:textColor="#android:color/black"
android:textSize="18sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="#+id/txt11"
app:layout_constraintStart_toStartOf="#+id/txt11"
app:layout_constraintTop_toBottomOf="#+id/txt11"
app:layout_constraintVertical_bias="0.26" />
</androidx.constraintlayout.widget.ConstraintLayout>
The problem is that you didn't set the ViewPager adapter
public class DialogWeeklyReport extends AppCompatDialogFragment {
...
#NonNull
#Override
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
...
viewPager = view.findViewById(R.id.viewPager);
...
adapter = new SliderAdapter(getActivity(), text);
viewPager.setAdapter(adapter); // <<<<<< change here
return builder.create();
}
...
Here is my test

How can I Overlay Play icon on top of Gridview Android?

I want Help to overlay a play icon on top of every grid item, if it contains video.Here is my Layout File of GridView. I was Trying to do, but i was not able to wire up all things.
Ps :- I am Newbie
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="2dp"
tools:context="com.techx.storysaver.ImageFragment">
<GridView
android:id="#+id/grid_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:horizontalSpacing="2dp"
android:listSelector="#drawable/griditem_selector"
android:numColumns="2"
android:drawSelectorOnTop="true"
android:stretchMode="columnWidth"
android:verticalSpacing="2dp" />
</FrameLayout>
Here is my ImageAdapter
public class ImageAdapter extends BaseAdapter {
private Context context;
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Pictures";
File f = new File(path);
File file[] = f.listFiles();
public ImageAdapter(Context c) {
context = c;
}
#Override
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
}
#Override
public int getCount() {
return file.length;
}
#Override
public Object getItem(int position) {
return file[position];
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Arrays.sort(file, LastModifiedFileComparator.LASTMODIFIED_REVERSE);
final String path = file[position].getAbsolutePath();
CheckableLayout l;
ImageView i;
if (convertView == null) {
i = new ImageView(context);
i.setScaleType(ImageView.ScaleType.CENTER_CROP);
int widthSize = getScreenWidth();
widthSize = widthSize / 2;
widthSize = widthSize - 8;
int heightSize = getScreenHeight();
heightSize = heightSize / 3;
heightSize = heightSize - 10;
i.setLayoutParams(new ViewGroup.LayoutParams(widthSize, heightSize));
i.setPadding(8, 8, 8, 8);
l = new CheckableLayout(context);
l.setLayoutParams(new GridView.LayoutParams(GridView.LayoutParams.WRAP_CONTENT, GridView.LayoutParams.WRAP_CONTENT));
l.addView(i);
} else {
l = (CheckableLayout) convertView;
i = (ImageView) l.getChildAt(0);
}
if (path.endsWith(".jpg") || path.endsWith(".jpeg") || path.endsWith(".png")) {
Glide
.with(context)
.load(file[position])
.into(i);
}
if (path.endsWith(".mp4")) {
Glide
.with(context)
.load(file[position])
.into(i);
}
return l;
}
public class CheckableLayout extends FrameLayout implements Checkable {
private boolean mChecked;
public CheckableLayout(Context context) {
super(context);
}
#SuppressWarnings("deprecation")
public void setChecked(boolean checked) {
mChecked = checked;
setBackgroundDrawable(checked ? getResources().getDrawable(R.drawable.item_selector) : null);
}
public boolean isChecked() {
return mChecked;
}
public void toggle() {
setChecked(!mChecked);
}
}
public static int getScreenWidth() {
return Resources.getSystem().getDisplayMetrics().widthPixels;
}
public static int getScreenHeight() {
return Resources.getSystem().getDisplayMetrics().heightPixels;
}
}
1. Create an layout XML for your GridView Item.
grid_item.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:card_view="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/tools"
android:id="#+id/card_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
card_view:cardCornerRadius="4dp"
card_view:cardUseCompatPadding="false"
card_view:cardPreventCornerOverlap="false">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/image"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:scaleType="centerCrop"
android:src="#drawable/sample_1" />
<ImageView
android:id="#+id/icon_play"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:src="#drawable/icon_play"/>
<TextView
android:id="#+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/image"
android:padding="8dp"
android:background="#CCFFFFFF"
android:text="This is simple title"
android:textColor="#000000" />
</RelativeLayout>
</android.support.v7.widget.CardView>
2. Use grid_item.xml from your adapter getView() method for each item:
#Override
public View getView(int pos, View convertView, ViewGroup parent)
{
Arrays.sort(file, LastModifiedFileComparator.LASTMODIFIED_REVERSE);
final String path = file[position].getAbsolutePath();
if(convertView == null)
{
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.grid_item, null);
}
ImageView imageView = (ImageView) convertView.findViewById(R.id.image);
ImageView iconPlay= (ImageView) convertView.findViewById(R.id.icon_play);
TextView textTitle= (TextView) convertView.findViewById(R.id.title);
// Image
if (path.endsWith(".jpg") || path.endsWith(".jpeg") || path.endsWith(".png")) {
Glide
.with(context)
.load(file[position])
.into(imageView);
// Hide play icon
iconPlay.setVisibility(View.GONE);
}
// Video
if (path.endsWith(".mp4")) {
Glide
.with(context)
.load(file[position])
.into(imageView);
// Show play icon
iconPlay.setVisibility(View.VISIBLE);
}
return convertView;
}
OUTPUT:
Hope this will help~

Add Progress bar while data loading from database

I use volley library to get data from database i use this code
public class R_arabic extends AppCompatActivity {
RequestQueue requestQueue;
ListView listView;
ArrayList<listitem_gib> listitems = new ArrayList<listitem_gib>();
String name, img, url, num;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_r_arabic);
listView = (ListView) findViewById(R.id.listView);
TextView textView_Title = (TextView) findViewById(R.id.textView2);
Intent intent = getIntent();
String story_type = intent.getStringExtra("story_type");
switch (story_type) {
case "arabic":
textView_Title.setText("arabic");
break;
case "romance":
textView_Title.setText("romance");
break;
case "motrgm":
textView_Title.setText("motrgm");
break;
case "ro3b":
textView_Title.setText("ro3b");
break;
case "siasa":
textView_Title.setText("siasa");
break;
}
String url = "http://grassyhat.com/android/" + story_type + ".php";
requestQueue = Volley.newRequestQueue(this);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url,
new Response.Listener<JSONObject>() {
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("all");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject respons = jsonArray.getJSONObject(i);
String id = respons.getString("id");
String name = respons.getString("name");
String img = respons.getString("img");
String url = respons.getString("url");
String num = respons.getString("num");
listitems.add(new listitem_gib(id, name, img, url, num));
}
} catch (JSONException e) {
e.printStackTrace();
}
listAllItme();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", "ERROR");
}
}
);
requestQueue.add(jsonObjectRequest);
}
public void listAllItme() {
ListAdapter lA = new listAdapter(listitems);
listView.setAdapter(lA);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
CheckInternetConnection cic = new CheckInternetConnection(getApplicationContext());
Boolean Ch = cic.isConnectingToInternet();
if (!Ch) {
Toast.makeText(R_arabic.this, "no connection", Toast.LENGTH_LONG).show();
} else {
Intent open = new Intent(R_arabic.this, rewaya_show.class);
open.putExtra("name", listitems.get(position).name);
open.putExtra("url", listitems.get(position).url);
open.putExtra("img", listitems.get(position).img);
open.putExtra("num", listitems.get(position).num);
startActivity(open);
showad++;
if (showad >= 5) {
showad = 0;
if (mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
}
}
}
}
});
}
class listAdapter extends BaseAdapter {
ArrayList<listitem_gib> lista = new ArrayList<listitem_gib>();
public listAdapter(ArrayList<listitem_gib> lista) {
this.lista = lista;
}
#Override
public int getCount() {
return lista.size();
}
#Override
public Object getItem(int position) {
return lista.get(position).name;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater layoutInflater = getLayoutInflater();
View view = layoutInflater.inflate(R.layout.row_item_gib, null);
TextView name = (TextView) view.findViewById(R.id.textView_gib);
ImageView img = (ImageView) view.findViewById(R.id.imageView_gib);
TextView num = (TextView) view.findViewById(R.id.textView_gib2);
name.setText(lista.get(position).name);
num.setText(lista.get(position).num);
Picasso.with(R_arabic.this).load("http://grassyhat.com/android/image/" + lista.get(position).img).into(img);
return view;
}
}
i want to add progress bar while data loading to avoid blank page
sorry i'm new in android and i google for that and don't get useful answer
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.kamal.ahmed.rewaya.R_arabic"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
android:background="#drawable/bg"
tools:showIn="#layout/app_bar_r_arabic">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/adView">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="40sp"
android:textStyle="bold"
android:textColor="#e873400c"
android:layout_gravity="center"
android:id="#+id/textView2" />
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/listView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:paddingRight="#dimen/activity_horizontal_margin"
android:divider="#drawable/div1"
android:dividerHeight="35dp" />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/progress_layout"
android:visibility="gone">
<ProgressBar
android:id="#+id/progress_bar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginLeft="100dp"
android:layout_marginBottom="60dp"
android:layout_weight="1"/>
<TextView
android:text="Download"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/progress_txt"
android:textSize="30sp"
android:textStyle="bold"
android:textColor="#e873400c"
android:layout_gravity="center"
android:layout_marginRight="90dp"
android:layout_marginBottom="60dp"
android:layout_weight="1" />
</LinearLayout>
Add progressBar in your activity_r_arabic
<ProgressBar
android:id="#+id/progress_bar"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
add ProgessBar progressBar; as global variable in your activity
and initialise it as
progressBar = (ProgessBar) findViewById(R.id.progress_bar);
and then In onResponse(JSONObject response) method add following line
progressBar.setVisibility(View.GONE)
EDIT
Make your linearLayout visible in xml
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/progress_layout"
android:visibility="visible">
<ProgressBar
android:id="#+id/progress_bar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginLeft="100dp"
android:layout_marginBottom="60dp"
android:layout_weight="1"/>
<TextView
android:text="Download"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/progress_txt"
android:textSize="30sp"
android:textStyle="bold"
android:textColor="#e873400c"
android:layout_gravity="center"
android:layout_marginRight="90dp"
android:layout_marginBottom="60dp"
android:layout_weight="1" />
</LinearLayout>
and inside onResponse(JSONObject response) method add following line
progress_layout.setVisibility(View.GONE)

Selections disappear when scrolling in listview, along with strange behaviour

I have run into some strange issues with my listview. I created a list using listview, along with a custom adapter to display rows with a text field and multiple images. I beleive that I have that part working well. I also put two buttons at the bottom of the listview so that I can select rows and modify them using the two buttons. I implemented highlighting by simply changing the background color and then setting a boolean flag that is part of each row so I can know what rows are highlighted. Now I am experiencing two issues. The first is that if I select a row and then scroll so that row is outside of the screen, then the row becomes un-highlighted, which is bad. I only want a row to become un-highlighted if the user clicks on it again or if a command is issued. The second problem is that once the adapter is updated or a row moves out of view, if you try to click on a row it will immediately un-highlight itself; this only happens once. After that happens then you can click on the row and it will stay highlighted. I would very much appreciate some help with this.
Regards.
HelmetList.java
public class HelmetList
{
public HelmetList (String name, String address, String img_hel, String img_rec, String img_bat,
String img_dsk, String img_str, Boolean selected)
{
super();
this.name = name;
this.address = address;
this.img_hel = img_hel;
this.img_rec = img_rec;
this.img_bat = img_bat;
this.img_dsk = img_dsk;
this.img_str = img_str;
this.selected = selected;
}
private String name;
private String address;
private String img_hel;
private String img_rec;
private String img_bat;
private String img_dsk;
private String img_str;
private Boolean selected;
public String getName ()
{
return name;
}
public void setName (String s_name)
{
this.name = s_name;
}
public String getAddress ()
{
return address;
}
public void setAddress (String s_address)
{
this.address = s_address;
}
public String getImgHel ()
{
return img_hel;
}
public void setImgHel (String s_img_hel)
{
this.img_hel = s_img_hel;
}
public String getImgRec ()
{
return img_rec;
}
public void setImgRec (String s_img_rec)
{
this.img_rec = s_img_rec;
}
public String getImgBat ()
{
return img_bat;
}
public void setImgBat (String s_img_bat)
{
this.img_bat = s_img_bat;
}
public String getImgDsk ()
{
return img_dsk;
}
public void setImgDsk (String s_img_dsk)
{
this.img_dsk = s_img_dsk;
}
public String getImgStr ()
{
return img_str;
}
public void setImgStr (String s_img_str)
{
this.img_str = s_img_str;
}
public Boolean getSelected ()
{
return selected;
}
public void setSelected (Boolean s_selected)
{
this.selected = s_selected;
}
}
HelmetListAdapter.java
public class HelmetListAdapter extends ArrayAdapter<HelmetList>
{
private int resource;
private LayoutInflater inflater;
private Context context;
public HelmetListAdapter (Context p_context, int p_resource, List<HelmetList> p_objects)
{
super (p_context, p_resource, p_objects);
resource = p_resource;
inflater = LayoutInflater.from (p_context);
context = p_context;
}
#Override
public View getView (int position, View convertView, ViewGroup parent)
{
convertView = ( RelativeLayout ) inflater.inflate( resource, null );
HelmetList Helmet = getItem (position);
TextView hname = (TextView) convertView.findViewById(R.id.h_name);
hname.setText(Helmet.getName ());
TextView haddress = (TextView) convertView.findViewById(R.id.h_address);
haddress.setText(Helmet.getAddress ());
ImageView himage = (ImageView) convertView.findViewById(R.id.h_image);
String uri = "drawable/" + Helmet.getImgHel();
int imageResource = context.getResources().getIdentifier(uri, null, context.getPackageName());
Drawable image = context.getResources().getDrawable(imageResource);
himage.setImageDrawable(image);
ImageView hrec = (ImageView) convertView.findViewById(R.id.h_rec);
uri = "drawable/" + Helmet.getImgRec();
imageResource = context.getResources().getIdentifier(uri, null, context.getPackageName());
image = context.getResources().getDrawable(imageResource);
hrec.setImageDrawable(image);
ImageView hlbat = (ImageView) convertView.findViewById(R.id.h_lb);
uri = "drawable/" + Helmet.getImgBat();
imageResource = context.getResources().getIdentifier(uri, null, context.getPackageName());
image = context.getResources().getDrawable(imageResource);
hlbat.setImageDrawable(image);
ImageView hldsk = (ImageView) convertView.findViewById(R.id.h_ld);
uri = "drawable/" + Helmet.getImgDsk();
imageResource = context.getResources().getIdentifier(uri, null, context.getPackageName());
image = context.getResources().getDrawable(imageResource);
hldsk.setImageDrawable(image);
ImageView hstr = (ImageView) convertView.findViewById(R.id.h_str);
uri = "drawable/" + Helmet.getImgStr();
imageResource = context.getResources().getIdentifier(uri, null, context.getPackageName());
image = context.getResources().getDrawable(imageResource);
hstr.setImageDrawable(image);
return convertView;
}
}
MainActivity.java
public class MainActivity extends Activity
{
private ListView lvhelmets;
private HelmetListAdapter adhelmets;
private Context ctx;
List<Integer> selected;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ctx = this;
List<HelmetList> helmetlist = new ArrayList<HelmetList>();
helmetlist.add(new HelmetList("Bell", "11111", "helmetpic0", "rec",
"bat", "mm", "str", Boolean.FALSE));
helmetlist.add(new HelmetList("Shoei", "33333", "helmetpic1", "rec",
"bat", "mm", "str", Boolean.FALSE));
helmetlist.add(new HelmetList("Harley Davidson", "55555", "helmetpic2", "rec",
"bat", "mm", "str", Boolean.FALSE));
helmetlist.add(new HelmetList("Joe Rocket", "77777", "helmetpic3", "rec",
"bat", "mm", "str", Boolean.FALSE));
lvhelmets = (ListView) findViewById(R.id.Helmet_list);
lvhelmets.setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE);
adhelmets = new HelmetListAdapter(ctx, R.layout.row_format, helmetlist);
lvhelmets.setAdapter (adhelmets);
Button price = (Button) findViewById(R.id.bPrice);
Button safety = (Button) findViewById(R.id.bSafety);
price.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
lvhelmets.setAdapter(adhelmets);
int count = lvhelmets.getCount();
for (int i = 0; i < count; i++)
{
HelmetList helmet = (HelmetList) lvhelmets.getItemAtPosition(i);
helmet.setSelected(Boolean.FALSE);
}
adhelmets.notifyDataSetChanged();
}
});
safety.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
lvhelmets.setAdapter(adhelmets);
int count = lvhelmets.getCount();
for (int i = 0; i < count; i++)
{
HelmetList helmet = (HelmetList) lvhelmets.getItemAtPosition(i);
helmet.setSelected(Boolean.FALSE);
}
adhelmets.notifyDataSetChanged();
}
});
lvhelmets.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
HelmetList helmet = (HelmetList) parent.getItemAtPosition(position);
if (!helmet.getSelected())
{
view.setBackgroundColor(Color.LTGRAY);
helmet.setSelected(Boolean.TRUE);
}
else
{
view.setBackgroundColor(Color.TRANSPARENT);
helmet.setSelected(Boolean.FALSE);
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ListView
android:id="#+id/Helmet_list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingTop="5dp"
android:choiceMode="multipleChoice"
android:layout_weight="1">
</ListView>
<LinearLayout
android:id="#+id/btnHolderLL"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button
android:id="#+id/bPrice"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:paddingRight="1dp"
android:paddingLeft="1dp"
android:textColor="#FFFFFF"
android:background="#222222"
android:text="Price"
android:clickable="true" />
<Button
android:id="#+id/bSafety"
android:layout_width="1dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:paddingRight="1dp"
android:paddingLeft="1dp"
android:textColor="#FFFFFF"
android:background="#222222"
android:text="Safety"
android:clickable="true" />
</LinearLayout>
</LinearLayout>
row_format.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="5dip" >
<!-- ListRow Left side Thumbnail image -->
<LinearLayout android:id="#+id/thumbnail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="3dip"
android:layout_alignParentLeft="true"
android:layout_marginRight="5dip">
<ImageView
android:id="#+id/h_image"
android:layout_width="50dip"
android:layout_height="50dip"
android:layout_marginLeft="5dip"/>
</LinearLayout>
<TextView
android:id="#+id/h_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/thumbnail"
android:layout_toRightOf="#+id/thumbnail"
android:textColor="#040404"
android:typeface="sans"
android:textSize="20dip"
android:layout_marginTop="5dip"
android:textStyle="bold"/>
<TextView
android:id="#+id/h_address"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#id/h_name"
android:textColor="#343434"
android:textSize="12dip"
android:layout_marginTop="1dip"
android:layout_toRightOf="#+id/thumbnail" />
<ImageView
android:id="#+id/h_rec"
android:layout_width="35dp"
android:layout_height="35dp"
android:layout_alignParentRight="true"
android:layout_marginRight="5dp"
android:layout_centerVertical="true" />
<ImageView
android:id="#+id/h_lb"
android:layout_width="35dp"
android:layout_height="35dp"
android:layout_alignParentRight="true"
android:layout_marginRight="45dp"
android:layout_centerVertical="true" />
<ImageView
android:id="#+id/h_ld"
android:layout_width="35dp"
android:layout_height="35dp"
android:layout_alignParentRight="true"
android:layout_marginRight="85dp"
android:layout_centerVertical="true" />
<ImageView
android:id="#+id/h_str"
android:layout_width="35dp"
android:layout_height="35dp"
android:layout_alignParentRight="true"
android:layout_marginRight="125dp"
android:layout_centerVertical="true" />
</RelativeLayout>
This happens because of the view recycling.
In the method getView() of your adapter, add the following piece of code :
if (!helmet.getSelected()) {
convertView.setBackgroundColor(Color.LTGRAY);
} else {
convertView.setBackgroundColor(Color.TRANSPARENT);
}
You might want to rewrite your view recycling by the way; the one you implemented is not effective at all.
A first step would be to add this :
#Override
public View getView (int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(resource, parent, false);
}
// continue the rest of the cell data filling
}

Android multiple lists using #id/android:list

I've got a new List of things that needs to be clicked but this one isn't working. onListItemClick is never called. I have another one in my app that has been working as expected and I can't figure out what the difference is. It occurs to me that maybe there's some conflict since they are both using the provided #id/android:list but they're in different Activities and I haven't found other people complaining about the same problem so I'm not sure.
Here is a bunch of code. I would appreciate any suggestions.
Working:
#Override
protected void onListItemClick(ListView l, View v, int position, long id)
{
super.onListItemClick(l, v, position, id);
// get the item that was clicked
v_ProjectInvestigatorSiteContact project = (v_ProjectInvestigatorSiteContact) this.getListAdapter().getItem(
position);
Intent myIntent = new Intent(this, Details.class);
myIntent.putExtra(res.getString(R.string.project), project);
startActivity(myIntent);
}// onListItemClick
Not Working:
#Override
protected void onListItemClick(ListView l, View v, int position, long id)
{
super.onListItemClick(l, v, position, id);
// get the item that was clicked
final v_SitePeople vSitePeople = (v_SitePeople) this.getListAdapter().getItem(
position);
AlertDialog.Builder builder = new AlertDialog.Builder(Share.this);
builder.setTitle(res.getString(R.string.forgot_password_check_dialog_title))
.setMessage(res.getString(R.string.share_check_dialog_text))
.setPositiveButton(res.getString(R.string.send), new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
sendShareEmail(vSitePeople);
}
}).setNegativeButton(res.getString(R.string.cancel), new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
// cancelled, so do nothing
}
});
AlertDialog msgBox = builder.create();
msgBox.show();
}// onListItemClick
Working XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffffff"
android:orientation="vertical" >
<!-- dummy item to prevent edittext from gaining focus on activity start -->
<LinearLayout
android:layout_width="0px"
android:layout_height="0px"
android:focusable="true"
android:focusableInTouchMode="true" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/title_background" >
<ImageView
android:id="#+id/logo"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_centerVertical="true"
android:layout_marginLeft="5dp"
android:scaleType="centerCrop"
android:src="#drawable/ic_logo" >
</ImageView>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/logo"
android:gravity="center"
android:paddingBottom="5dp"
android:paddingLeft="50dp"
android:paddingRight="60dp"
android:paddingTop="5dp"
android:text="#string/app_header"
android:textColor="#ffffffff"
android:textSize="15sp"
android:textStyle="bold" />
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/search_gradient" >
<ImageView
android:id="#+id/searchBoxIcon"
android:layout_width="38dp"
android:layout_height="38dp"
android:layout_centerVertical="true"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:scaleType="centerCrop"
android:src="#drawable/action_search" >
</ImageView>
<EditText
android:id="#+id/searchBox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="#+id/searchBoxIcon"
android:layout_marginRight="8dp"
android:layout_marginTop="4dp"
android:layout_toRightOf="#+id/searchBoxIcon"
android:background="#drawable/search_box"
android:hint="#string/search_hint"
android:inputType="text"
android:maxLines="1"
android:minHeight="30sp"
android:paddingBottom="2dp"
android:paddingLeft="25sp"
android:paddingTop="2dp"
android:textColor="#ff000000" />
</RelativeLayout>
<ListView
android:id="#id/android:list"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="#color/divider_gray"
android:cacheColorHint="#00000000"
android:divider="#color/divider_gray"
android:dividerHeight="1dp"
android:footerDividersEnabled="false"
android:headerDividersEnabled="false" />
<TextView
android:id="#+id/android:empty"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="#string/loading"
android:textColor="#color/loading_gray"
android:textSize="20sp" />
</LinearLayout>
Not Working XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffffff"
android:orientation="vertical" >
<!-- dummy item to prevent edittext from gaining focus on activity start -->
<LinearLayout
android:layout_width="0px"
android:layout_height="0px"
android:focusable="true"
android:focusableInTouchMode="true" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/title_background" >
<ImageView
android:id="#+id/logo"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_centerVertical="true"
android:layout_marginLeft="5dp"
android:scaleType="centerCrop"
android:src="#drawable/ic_logo" >
</ImageView>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/logo"
android:gravity="center"
android:paddingBottom="5dp"
android:paddingLeft="50dp"
android:paddingRight="60dp"
android:paddingTop="5dp"
android:text="#string/share_header"
android:textColor="#ffffffff"
android:textSize="15sp"
android:textStyle="bold" />
</RelativeLayout>
<ListView
android:id="#id/android:list"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="#color/divider_gray"
android:cacheColorHint="#00000000"
android:divider="#color/divider_gray"
android:dividerHeight="1dp"
android:footerDividersEnabled="false"
android:headerDividersEnabled="false" />
<TextView
android:id="#+id/android:empty"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="#string/loading"
android:textColor="#color/loading_gray"
android:textSize="20sp" />
</LinearLayout>
Here is more on how the broken one works, just in case you want more code.
Not Working Row XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:layout_weight="1"
android:baselineAligned="false"
android:orientation="vertical"
android:padding="6dp"
android:background="#ffffffff"
android:layout_margin="10dp" >
<TextView
android:id="#+id/toptext"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_toLeftOf="#id/moreInfo"
android:gravity="center_vertical"
android:minHeight="20sp"
android:textColor="#ff000000"
android:textStyle="bold" />
</RelativeLayout>
Not Working View Adapter
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
ViewHolder holder = null;
if (convertView == null)
{
holder = new ViewHolder();
LayoutInflater vi = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.share_row, null);
convertView.setTag(holder);
}// if
else
{
holder = (ViewHolder) convertView.getTag();
}
v_SitePeople i = items.get(position);
if (i != null)
{
TextView topText = (TextView) convertView.findViewById(R.id.toptext);
topText.setGravity(Gravity.CENTER_VERTICAL);
topText.setMinHeight(40);
if (topText != null)
{
if (i.SitePerson != null)
{
if (i.PersonTitle != null)
{
topText.setText(String.format(i.SitePerson + ", " + i.PersonTitle));
}
else
{
topText.setText(i.SitePerson);
}
}// if has ProtocolNumber
else
{
if (i.Nickname != null)
{
topText.setText(i.Nickname);
}
}// if does not have ProtocolNumber
}// if
}// if
return convertView;
}// getView
Thank you so much for your help.
More code as requested.
Working setListAdapter:
public void updateDisplay(ArrayList<v_ProjectInvestigatorSiteContact> vProjectInvestigatorSiteContactList)
{
if (fullAdapter != null)
{
if (fullAdapter.isEmpty())
{
fullAdapter = new ProjectAdapter(this, R.layout.row, vProjectInvestigatorSiteContactList);
fullAdapter = reOrder(fullAdapter);
setListAdapter(fullAdapter);
}
else
{
filteredAdapter = new ProjectAdapter(this, R.layout.row, vProjectInvestigatorSiteContactList);
filteredAdapter = reOrder(filteredAdapter);
setListAdapter(filteredAdapter);
}
}
else
{
fullAdapter = new ProjectAdapter(this, R.layout.row, vProjectInvestigatorSiteContactList);
fullAdapter = reOrder(fullAdapter);
setListAdapter(fullAdapter);
}
}// updateDisplay
Working list setup:
private class DownloadProjectsTask extends AsyncTask<String, Void, ArrayList<v_ProjectInvestigatorSiteContact>> {
#Override
protected ArrayList<v_ProjectInvestigatorSiteContact> doInBackground(String... URLs)
{
return ProjectsHelper.parseProjects(URLs, CurrentStudies.this);
}// doInBackground
#Override
protected void onPostExecute(ArrayList<v_ProjectInvestigatorSiteContact> vProjectInvestigatorSiteContactList)
{
updateDisplay(vProjectInvestigatorSiteContactList);
}// onPostExecute
}// DownloadProjectsTask
Working adapter:
public class ProjectAdapter extends ArrayAdapter {
private ArrayList items;
private Resources res;
public ProjectAdapter(Context context, int textViewResourceId, ArrayList<v_ProjectInvestigatorSiteContact> items)
{
super(context, textViewResourceId, items);
this.items = items;
this.res = context.getResources();
}// ProjectAdapater
#Override
public int getCount()
{
return items.size();
}
#Override
public v_ProjectInvestigatorSiteContact getItem(int position)
{
return items.get(position);
}
#Override
public long getItemId(int position)
{
return position;
}
#Override
public int getViewTypeCount()
{
return 2;
}
#Override
public int getItemViewType(int position)
{
if (items.get(position).ProjectID == null)
{
return 0;
}
else
{
return 1;
}
}
#Override
public boolean isEnabled(int position)
{
if (getItemViewType(position) == 0)
{
return false;
}
return true;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
ViewHolder holder = null;
int type = getItemViewType(position);
if (convertView == null)
{
holder = new ViewHolder();
LayoutInflater vi = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (type == 0)
{
convertView = vi.inflate(R.layout.row_header, null);
}
else
{
convertView = vi.inflate(R.layout.row, null);
}
convertView.setTag(holder);
}// if
else
{
holder = (ViewHolder) convertView.getTag();
}
v_ProjectInvestigatorSiteContact i = items.get(position);
if (i != null)
{
TextView topText = (TextView) convertView.findViewById(R.id.toptext);
TextView bottomText = (TextView) convertView.findViewById(R.id.bottomtext);
if (topText != null)
{
if (i.ProtocolNumber != null)
{
if (i.WebIndication != null)
{
topText.setText(i.ProtocolNumber);
bottomText.setText(i.WebIndication);
}
else if (i.ProjectName != null)
{
topText.setText(i.ProtocolNumber);
bottomText.setText(i.ProjectName);
}
}// if has ProtocolNumber
else
{
if (i.WebIndication != null)
{
topText.setText(i.WebIndication);
topText.setMinHeight(40);
topText.setGravity(Gravity.CENTER_VERTICAL);
}
else if (i.ProjectName != null)
{
topText.setText(i.ProjectName);
topText.setMinHeight(40);
topText.setGravity(Gravity.CENTER_VERTICAL);
}
else
{
topText.setText(i.SiteID);
topText.setMinHeight(40);
topText.setGravity(Gravity.CENTER_VERTICAL);
}
}// if does not have ProtocolNumber
}// if
// Coming Soon logic
if (i.ProjectStatusID != null)
{
if (i.ProjectStatusID.equals(res.getString(R.string.feasibility_id)))
{
topText.setTextColor(res.getColor(R.color.coming_soon_gray));
bottomText.setText("(Coming Soon)");
}
else {
topText.setTextColor(Color.BLACK);
}
}//if
if (bottomText != null)
{
if (type == 0)
{
if (position == getCount() - 1 || getItemViewType(position + 1) == 0)
{
bottomText.setVisibility(View.VISIBLE);
bottomText.setText(res.getString(R.string.no_studies));
bottomText.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, 0, (float) 1.0));
}
else
{
bottomText.setVisibility(View.GONE);
}
}// header followed by another header, or end of list
}// if
//recenters row headers
if (type == 0)
{
topText.setGravity(Gravity.CENTER);
}
}// if
return convertView;
}// getView
public static class ViewHolder {
public TextView textView;
}
}// ProjectAdapter
Not Working setListAdapter:
public void updateDisplay(ArrayList<v_SitePeople> vSitePeopleShareList)
{
adapter = new ShareAdapter(this, R.layout.share_row, vSitePeopleShareList);
setListAdapter(adapter);
}// updateDisplay
Not Working list setup:
private class DownloadShareTask extends AsyncTask<String, Void, ArrayList<v_SitePeople>> {
#Override
protected ArrayList<v_SitePeople> doInBackground(String... params)
{
return ProjectsHelper.getSharePeople(params[0], Share.this);
}// doInBackground
#Override
protected void onPostExecute(ArrayList<v_SitePeople> vSitePeopleShareList)
{
updateDisplay(vSitePeopleShareList);
}// onPostExecute
}// DownloadProjectsTask
I figured it out. I didn't ever post the relevant code, or I'm sure you guys would have spotted it for me.
I copied a non working adapter from a working piece of code which returns false if the viewType is 0. And since my second list only has one type, everything was disabled.
Thank you all for your efforts. I apologize that I didn't give you the correct code.

Categories