I want to be able to click on buttons to navigate forward and backward through several views as well as swiping left or right between views.
So I decided to implement the ViewPager for swiping between multiple views.
Here's my code:
layout xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#color/white"
>
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/viewPager"/>
<ImageView
android:id="#+id/apple"
android:layout_width="200sp"
android:layout_height="150sp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:src="#drawable/apple"
android:contentDescription="apple"/>
<TextView
android:id="#+id/number"
android:layout_width="100sp"
android:layout_height="55sp"
android:layout_marginTop="47dp"
android:layout_below="#+id/apple" android:layout_alignStart="#+id/apple"/>
<Button
android:id="#+id/save"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/save"
android:layout_alignTop="#+id/ignore" android:layout_toStartOf="#+id/apple"/>
<Button
android:id="#+id/ignore"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/Ignore"
android:layout_alignParentBottom="true" android:layout_toEndOf="#+id/apple"/>
<ImageView
android:id="#+id/back_nav_arrow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_action_back"
android:contentDescription="back">
</ImageView>
<ImageView
android:id="#+id/forward_nav_arrow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_action_forward"
android:layout_alignParentTop="true" android:layout_alignParentEnd="true"
android:contentDescription="forward">
</ImageView>
</RelativeLayout>
Here's my activity:
public class CollectionPager extends Activity {
private PagerAdapter pagerAdapter;
ActionBar actionbar;
MyAdapter myAdapter;
private Context context;
private TextView textView;
private int currentPage;
ViewPager viewPager;
int progressChanged = 0;
public static final String TAG = "CollectionPager";
public CollectionPager() {
context = this;
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.collection);
viewPager = (ViewPager) findViewById(R.id.viewPager);
myAdapter = new MyAdapter();
viewPager.setAdapter(myAdapter);
ActionBar actionBar = getActionBar();
if (actionBar != null) {
actionBar.hide();
}
//Initialize the back button and add an onClick event listener to the button
final ImageView back_button = (ImageView) findViewById(R.id.back_nav_arrow);
back_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
//it doesn't matter if you're already in the first item
viewPager.setCurrentItem(viewPager.getCurrentItem() - 1);
}
});
//Initialize the forward button and add an onClick event listener to the button
final ImageView forward_button = (ImageView) findViewById(R.id.forward_nav_arrow);
forward_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
//it doesn't matter if you're already in the last item
viewPager.setCurrentItem(viewPager.getCurrentItem() + 1);
}
});
final Button save_button = (Button) findViewById(R.id.save);
save_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
//save
}
});
final Button ignore_button = (Button) findViewById(R.id.ignore);
ignore_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
//ignore
}
});
//Attach the page change listener inside the activity
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
// This method will be invoked when the current page is scrolled
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
//This method will be invoked when a new page becomes selected
#Override
public void onPageSelected(int position) {
//get position
currentPage = position;
}
// Called when the scroll state changes:
// SCROLL_STATE_IDLE, SCROLL_STATE_DRAGGING, SCROLL_STATE_SETTLING
#Override
public void onPageScrollStateChanged(int i) {
//get state
}
});
}
private class MyAdapter extends PagerAdapter {
int NumberOfPages = 10;
LayoutInflater inflater = (LayoutInflater) CollectionPager.this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
#Override
public int getCount() {
return NumberOfPages;
}
#Override
public Object instantiateItem(ViewGroup parent, int position) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.collection, parent, false);
ImageView imageView = (ImageView) view
.findViewById(R.id.apple);
imageView.setImageResource(R.drawable.apple);
parent.addView(view,0);
return view;
}
#Override
public void destroyItem(ViewGroup parent, int position, Object object) {
((ViewPager) parent).removeView((View) object);
}
#Override
public boolean isViewFromObject(View parent, Object object) {
return parent== ((View) object);
}
#Override
public Parcelable saveState() {
return null;
}
}
}
The onClickEvent is detected but here's a screenshot on what is happening to the view. Two view on top of each other. One view is fixed on the screen and the other one is scrolling correctly.
I'm not sure why this happens. What is causing this to occur in my code?
EDIT: Here's a video highlighting the issue: https://www.dropbox.com/s/6x5qa16xyttzrwa/VIDEO0041.mp4?dl=0
Change
#Override
public boolean isViewFromObject(View parent, Object object) {
return parent== ((View) object);
}
to
#Override
public boolean isViewFromObject(View v, Object o) {
return parent == object;
}
Update:
After watching your movie your problem is you put some static wedget on the top of your viewpager, so remove that, which means your layout will become something like this:
This is your main_activity.xml you must assign it to your activity by function setContentView
<?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="fill_parent"
android:background="#color/white"
>
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/viewPager"/>
</RelativeLayout>
then at instantiateItem use below layout:
<?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="fill_parent"
android:background="#color/white"
>
<ImageView
android:id="#+id/apple"
android:layout_width="200sp"
android:layout_height="150sp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:src="#drawable/apple"
android:contentDescription="apple"/>
<TextView
android:id="#+id/number"
android:layout_width="100sp"
android:layout_height="55sp"
android:layout_marginTop="47dp"
android:layout_below="#+id/apple" android:layout_alignStart="#+id/apple"/>
<Button
android:id="#+id/save"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/save"
android:layout_alignTop="#+id/ignore" android:layout_toStartOf="#+id/apple"/>
<Button
android:id="#+id/ignore"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/Ignore"
android:layout_alignParentBottom="true" android:layout_toEndOf="#+id/apple"/>
<ImageView
android:id="#+id/back_nav_arrow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_action_back"
android:contentDescription="back">
</ImageView>
<ImageView
android:id="#+id/forward_nav_arrow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_action_forward"
android:layout_alignParentTop="true" android:layout_alignParentEnd="true"
android:contentDescription="forward">
</ImageView>
your main activity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.collection);
viewPager = (ViewPager) findViewById(R.id.viewPager);
myAdapter = new MyAdapter();
viewPager.setAdapter(myAdapter);
ActionBar actionBar = getActionBar();
if (actionBar != null) {
actionBar.hide();
}
//Attach the page change listener inside the activity
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
// This method will be invoked when the current page is scrolled
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
//This method will be invoked when a new page becomes selected
#Override
public void onPageSelected(int position) {
//get position
currentPage = position;
}
// Called when the scroll state changes:
// SCROLL_STATE_IDLE, SCROLL_STATE_DRAGGING, SCROLL_STATE_SETTLING
#Override
public void onPageScrollStateChanged(int i) {
//get state
}
});
}
then assign your click listener of your main activity at this function
#Override
public Object instantiateItem(ViewGroup parent, int position) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.collection, parent, false);
ImageView imageView = (ImageView) view
.findViewById(R.id.apple);
imageView.setImageResource(R.drawable.apple);
final ImageView back_button = (ImageView) view.findViewById(R.id.back_nav_arrow);
back_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
//it doesn't matter if you're already in the first item
viewPager.setCurrentItem(viewPager.getCurrentItem() - 1);
}
});
parent.addView(view,0);
return view;
}
Related
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("•"));
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
I have an xml for generating a listview with a checkbox as below:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="10dp" >
<CheckBox
android:id="#+id/book_check"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignParentRight="true"
android:checked="false" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toLeftOf="#+id/book_check"
android:orientation="horizontal"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:src="#drawable/finger" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/book_title"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingTop="5dp"
android:text="Title"
android:textColor="#000"
android:textSize="22sp" />
<TextView
android:text="Description"
android:id="#+id/book_descri"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#FF2500"
android:textSize="18sp" />
</LinearLayout>
</LinearLayout>
</RelativeLayout>
In my custom class I have the following code to help me manage the data I am getting from my little database
private class SbListAdapter extends ArrayAdapter<SbItem> {
ArrayList<SbItem> SongBookList;
public SbListAdapter(Context context, int textViewResourceId,
ArrayList<SbItem> SongBookList) {
super(context, textViewResourceId, SongBookList);
this.SongBookList = new ArrayList<SbItem>();
this.SongBookList.addAll(SongBookList);
}
private class ViewHolder {
CheckBox book;
TextView title;
TextView descri;
}
#SuppressLint("InflateParams")
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null; Log.v("ConvertView", String.valueOf(position));
if (convertView == null) {
LayoutInflater vi = (LayoutInflater)getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.cc_list_select, null);
holder = new ViewHolder();
holder.title = (TextView) convertView.findViewById(R.id.book_title);
holder.descri = (TextView) convertView.findViewById(R.id.book_descri);
holder.book = (CheckBox) convertView.findViewById(R.id.book_check);
convertView.setTag(holder);
holder.book.setOnClickListener( new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v ;
SbItem SbItem = (SbItem) cb.getTag();
SbItem.setSelected(cb.isChecked());
}
});
} else {
holder = (ViewHolder) convertView.getTag();
}
SbItem SbItem = SongBookList.get(position);
holder.title.setText(SbItem.getBook());
holder.descri.setText(SbItem.getDescri());
holder.book.setChecked(SbItem.isSelected());
holder.book.setTag(SbItem);
return convertView;
}
}
My desire is that when the text in line one and that in line is clicked that the checkbox is checked or unchecked because currently this only works when only the checkbox is clicked.
If I try to type cast it just gives an error. For instance this can not work:
holder.title.setOnClickListener( new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v ;
SbItem SbItem = (SbItem) cb.getTag();
SbItem.setSelected(cb.isChecked());
}
});
I just needs to work when users click anywhere on that item just like in settings activity.
I have tried to do this:
convertView.setOnClickListener( new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v ;
SbItem SbItem = (SbItem) cb.getTag();
SbItem.setSelected(cb.isChecked());
}
});
but when debugging the crashes and the error on the console is:
08-31 13:25:19.793: E/AndroidRuntime(24214):
java.lang.ClassCastException: android.widget.RelativeLayout cannot be
cast to android.widget.CheckBox
Try this:
From your activity or wherever you init your listview:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
//here update the status of your SbItem in the position of your arraylist and then notify the adapter
sblist.get(position).setSelected(!sblist.get(position).isSelected());
adapter.notifyDataSetChanged();
}
});
Also remove all your click listeners from your adapter.
UPDATE
In your SbItem class add setter:
public void setSelected(boolean s){
this.selected=s;
}
Also i assume that your getter returns the selected property
public boolean isSelected(){
return selected;
}
Use below event for change CheckBox State
holder.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
checkbox.setChecked(true);
} else {
checkbox.setChecked(false);
}
}
});
As your question you need to change your code.
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
holder.book.performClick();
}
});
Now use setOnCheckedChangeListener for checkbox.
holder.book.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
buttonView.setChecked(true);
// do your stuff
} else {
buttonView.setChecked(false);
// do your stuff
}
}
});
My Listview app gets its data and background color of itemview from custom adapter ListAdapter.class.i also need to set the currently selected list items value in a textview below listview,but the setOnItemClickListener in MAinActivity is not executing.pls help.
This is my list view app:
Layout image
MainActivity.java
public class MainActivity extends Activity {
private static ListAdapterclass adapter;
ListView lv;
TextView tv2;
private final String android_versions[]={
"Donut",
"Eclair",
"Froyo",
"Gingerbread",
"Honeycomb",
"Ice Cream Sandwich",
"Jelly Bean",
"KitKat",
"Lollipop",
"Marshmallow"
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initViews();
}
private void initViews() {
lv = (ListView) findViewById(R.id.listView1);
tv2 = (TextView) findViewById(R.id.selected);
adapter = new ListAdapterclass(getApplicationContext(), android_versions);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(getApplicationContext(), "hiiiiiiiii", Toast.LENGTH_SHORT).show();
System.out.println("********************** INSIDE ONITEMCLICKLISTNER IN MAIN ACTIVITY ******************");
String ver_name = (lv.getItemAtPosition(i)).toString();
tv2 = (TextView) findViewById(R.id.selected);
tv2.setText(ver_name);
}
});
}
}
ListAdapter.class
public class ListAdapterclass extends ArrayAdapter implements AdapterView.OnItemClickListener{
private String android_versionNames[];
Context mContext;
public int row_index=-1;
#Override
public void onItemClick(AdapterView<?> adapterView, View v, int i, long l) {
int position=(Integer)v.getTag();
String ver_name=getItem(position).toString();
}
private static class ViewHolder{
TextView tv;
LinearLayout LL;
TextView tv2;
}
public ListAdapterclass(Context context,String android_versionnames[]) {
super(context, R.layout.list_item,android_versionnames);
this.android_versionNames=android_versionnames;
this.mContext=context;
System.out.println(" ???????????????????????? Inside dataadapter,Android names : ?????????????????????????????\n ");
for(int i=0;i<android_versionnames.length;i++){
System.out.println("\n"+android_versionnames[i]);
}
}
private int lastPosition=-1;
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
String ver_name=getItem(position).toString();
final ViewHolder viewHolder;
final View result;
if(convertView==null){
viewHolder=new ViewHolder();
LayoutInflater inflater=LayoutInflater.from(getContext());
convertView=inflater.inflate(R.layout.list_item,parent,false);
viewHolder.tv=(TextView)convertView.findViewById(R.id.label);
viewHolder.LL=(LinearLayout) convertView.findViewById(R.id.linearLayout_1);
viewHolder.tv2=(TextView)convertView.findViewById(R.id.selected);
result=convertView;
convertView.setTag(viewHolder);
}else{
viewHolder=(ViewHolder) convertView.getTag();
result=convertView;
}
lastPosition=position;
viewHolder.tv.setText(ver_name);
viewHolder.LL.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
row_index=position;
notifyDataSetChanged();
}
});
if(row_index==position){
viewHolder.LL.setBackgroundColor(Color.parseColor("#409de1"));
viewHolder.tv.setTextColor(Color.parseColor("#ffffff"));
}
else
{
viewHolder.LL.setBackgroundColor(Color.parseColor("#ffffff"));
viewHolder.tv.setTextColor(Color.parseColor("#000000"));
}
return convertView;
}
}
ActivityMain.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.cybraum.test.listviewcolorchange.MainActivity"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:clickable="true"
android:layout_weight="1"
>
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/listView1"
>
</ListView>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight=".2"
android:id="#+id/linearLayout_2"
android:orientation="horizontal"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Selected : "
android:textStyle="bold"
android:layout_gravity="center"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
android:text="text"
android:id="#+id/selected"
android:layout_gravity="center"/>
</LinearLayout>
</LinearLayout>
listitem.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:id="#+id/linearLayout_1"
android:padding="10dp">
<TextView
android:id="#+id/label"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dip"
android:textSize="16dip"
android:textStyle="bold"
android:textColor="#000000"
android:gravity="center">
</TextView>
</LinearLayout>
what is the problem?
Remove viewHolder.LL.setOnClickListener listener from adapter and
In your adapter add a method to update row_index:
public void changeIndex(int rowIndex){
this.row_index = rowIndex;
notifyDataSetChanged();
}
Call this method from onItemClickListener event:
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
adapter.changeIndex(i);//This will give you the same result of viewHolder.LL.setOnClickListener as you are doing
//Do whatever you are doing previously
}
});
If you take click event from adapter then listview itemclick could not work if you need adapter click event and listview item click please refer the link,
How to make imageView clickable from OnItemClickListener?
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
long viewId = view.getId();
if (viewId == R.id.button1) {
Toast.makeText(this, "Button 1 clicked", Toast.LENGTH_SHORT).show();
} else if (viewId == R.id.button2) {
Toast.makeText(this, "Button 2 clicked", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "ListView clicked" + id, Toast.LENGTH_SHORT).show();
}
}
In adapter:
viewHolder.Btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
((ListView) parent).performItemClick(v, position, 0); // Let the event be handled in onItemClick()
}
Use:
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(getApplicationContext(), "hiiiiiiiii", Toast.LENGTH_SHORT).show();
System.out.println("********************** INSIDE ONITEMCLICKLISTNER IN MAIN ACTIVITY ******************");
String ver_name = (lv.getItemAtPosition(i)).toString();
tv2 = (TextView) findViewById(R.id.selected);
tv2.setText(ver_name);
}
});
And from adapter remove
implements AdapterView.OnItemClickListener
You need to remove your adaptor from the setOnClickListner()
Try to change Your method with
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Object o = prestListView.getItemAtPosition(position);
prestationEco str=(prestationEco)o;//As you are using Default String Adapter
Toast.makeText(getBaseContext(),str.getTitle(),Toast.LENGTH_SHORT).show();
}
});
change listview xml
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clickable="true"
android:focusable="true"></ListView>
remove AdapterView.OnItemClickListener from adapter class
public class ListAdapterclass extends ArrayAdapter {
}
change listview xml
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clickable="true"
android:focusable="true">
</ListView>
remove AdapterView.OnItemClickListener from adapter class
public class ListAdapterclass extends ArrayAdapter {
}
How can I change the text size of TextView of a fragment. I need it, because text size is small, maybe some users want it to get bigger.
I see, some people advise to use seekbar, or pinch-to-zoom but I can not make it work in a fragment.
Thanks for your help.
my fragment_one.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="org.aultoon.webovietab.fragments.OneFragment"
android:id="#+id/oneFragmentId"
>
<ScrollView
android:id="#+id/scrollView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fadingEdge="none"
android:fillViewport="true"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_gravity="top|center"
android:gravity="center"
>
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/tvFragmentOne"
android:text="#string/turkce1"
android:textSize="27sp"
android:textIsSelectable="true"
android:layout_margin="10dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
/>
</RelativeLayout>
</ScrollView>
here is the my OneFragment.java
public class OneFragment extends Fragment {
//static WebView mWebview;
public OneFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_one, container, false);
return rootView;
}
}
here is the my activity
public class SimpleTabsActivity extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_simple_tabs);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new OneFragment(), "tab1");
adapter.addFragment(new TwoFragment(), "tab2");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.aboutMenuItem:
Intent i = new Intent(this, About_Activity.class);
startActivity(i);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
First, please read the following Q&A about the textsize "sp" unit in android. You should understand why it used sp as unit for textView and your question should be solved.
Should use "sp" instead of "dp" for text sizes
What is the difference between "px", "dp", "dip" and "sp" on Android?
Android sp vs dp texts - what would adjust the 'scale' and what is the philosophy of support
http://www.singhajit.com/tutorial-1-android-ui-desgin-and-styling/
Now, you should know the usage of "sp" unit in TextView since it can be adjusted due to the user accessibility setting. That's mean if your boss cannot see it clearly, he/she can set the font size setting in the devices instead of code change.
If you still need workaround for the programming. Here is the solution
I have added the seekbar in your fragment layout.
Update xml.
<RelativeLayout android:id="#+id/oneFragmentId"
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"
>
<SeekBar
android:id="#+id/seekBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"/>
<ScrollView
android:id="#+id/scrollView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/seekBar"
android:fadingEdge="none"
android:fillViewport="true"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="top|center"
android:gravity="center"
android:orientation="vertical"
>
<TextView
android:id="#+id/tvFragmentOne"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_margin="10dp"
android:text="Hello world"
android:textIsSelectable="true"
android:textSize="27sp"
/>
</RelativeLayout>
</ScrollView>
</RelativeLayout>
I have change your textView text as "Hello world" for testing, please change back to your own string resource.
Here is the fragment code.
public class OneFragment extends Fragment {
//static WebView mWebview;
public OneFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_one, container, false);
final TextView tvFragmentOne = (TextView) rootView.findViewById(R.id.tvFragmentOne);
SeekBar lSeekBar = (SeekBar) rootView.findViewById(R.id.seekBar);
lSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
tvFragmentOne.setTextSize(progress);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
return rootView;
}
}
If you like to use other control pinch to zoom, up/down button or other control component to change the text size of the textview, you can do it with the following procedures:
Change other widget instead of seekbar
Change the listener for listening the component control change( like OnSeekBarChangeListener )
Reset the textView size
I'm removing images from a gridview when a button is pressed.
The images does remove fine and the gridview also updates with the call "adapter.notifyDataSetChanged();".
When an imageview is removed another image next to this position should take its position. This happens, but the image here won't reload so there's just a blank space? How can I get this imageview to reload its image?
The problem:
Here is my gridadapter:
public class FavoriteMovieGridAdapter extends BaseAdapter {
Context context;
ArrayList<DataFavorites> List;
FavoritesMovie fragment;
private static LayoutInflater inflater = null;
FavoriteMovieGridAdapter adapter = this;
public FavoriteMovieGridAdapter(Context context, ArrayList<DataFavorites> List, FavoritesMovie fragment) {
this.context = context;
this.List = List;
this.fragment = fragment;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return List.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// Avoid unneccessary calls to findViewById() on each row
final ViewHolder holder;
/*
* If convertView is not null, reuse it directly, no inflation
* Only inflate a new View when the convertView is null.
*/
if (convertView == null) {
convertView = inflater.inflate(R.layout.favorite_grid_item, null);
holder = new ViewHolder();
holder.poster = (ImageView) convertView.findViewById(R.id.upcoming_image);
holder.editbutton = (ImageView) convertView.findViewById(R.id.delete_item);
// The tag can be any Object, this just happens to be the ViewHolder
convertView.setTag(holder);
}
else{
// Get the ViewHolder back to get fast access to the TextView
// and the ImageView.
holder = (ViewHolder) convertView.getTag();
}
final View finalConvertView = convertView;
final DataFavorites e;
new DataFavorites();
e = List.get(position);
String url = String.valueOf(e.getUrl());
// load image url into poster
// Seems as if this doesn't run for the imageview next to this when this view is removed?
Picasso.with(context).load(url).fit().placeholder(R.drawable.movie_back).into(holder.poster);
// Create onclick and show edit button
convertView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
// show edit button
holder.editbutton.setVisibility(View.VISIBLE);
YoYo.with(Techniques.FadeIn).duration(700).playOn(finalConvertView.findViewById(R.id.delete_item));
// onclick edit button remove item and update gridview
holder.editbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
YoYo.with(Techniques.ZoomOut).duration(700).playOn(finalConvertView.findViewById(R.id.favorite_relative));
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
adapter.List.remove(e);
adapter.notifyDataSetChanged();
// Delete specific movie from data base
DatabaseHandlerMovie db = new DatabaseHandlerMovie(context);
// Reading all movies
db.deleteMovie(e);
}
}, 1000);
}
});
return false;
}
});
return convertView;
}
static class ViewHolder {
ImageView poster;
ImageView editbutton;
}
}
My grid item layout:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="#+id/favorite_relative"
android:layout_centerHorizontal="true"
android:gravity="center_horizontal">
<ImageView android:layout_width="123.3dp"
android:layout_height="185.3dp"
android:id="#+id/upcoming_image"
android:scaleType="fitXY" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/delete_item"
android:src="#drawable/ic_remove_circle_outline_white_24dp"
android:tint="#color/colorPrimaryDark"
android:clickable="true"
android:visibility="gone"
android:layout_alignRight="#+id/upcoming_image"
android:layout_alignEnd="#+id/upcoming_image"/>
</RelativeLayout>
My grid layout:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
tools:context=".Favorites"
android:background="#FFFFFF"
android:focusableInTouchMode="true">
<GridView
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:id="#+id/movies_gridlayout"
android:paddingRight="-1dp"
android:paddingEnd="-1dp"
android:numColumns="3"
android:background="#ffffff"
android:visibility="invisible"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:id="#+id/favorite_none"
android:text="No favorite movies found"
android:textSize="15sp"
android:visibility="gone"
android:textColor="#color/SecondaryText"
/>
<ProgressBar
android:id="#+id/progressBar"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:visibility="gone"
>
</ProgressBar>
</FrameLayout>
Turns out a 3rd-party lib was causing this:
YoYo.with(Techniques.ZoomOut).duration(700).playOn(finalConvertView.findViewById(R.id.favorite_relative));
you will have adapter and mainactivity for gridview
So u will have to implement public interface in both of them to communicate
following code may help you :)
In Adapter class add following code
private OnItemClickListner onItemClickListner;
public MyAdapter(Context c, List<PDFDoc> pdfDocs,OnItemClickListner onItemClickListner) {
this.context = c;
this.pdfDocs = pdfDocs;
this.onItemClickListner=onItemClickListner;
}
public interface OnItemClickListner {
void removefromadapter(int position);
}
ImageButton imageButton = view.findViewById(R.id.cancelid);
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// write your stuff here
onItemClickListner.removefromadapter(position);
}
});
In MainActivity of gridview add following code
implements OnItemClickListner required**
public class addclient_fragment extends Fragment implements MyAdapter.OnItemClickListner {
you will required to add this method in mainactivity
#Override
public void removefromadapter(int position) {
// write your stuff here
}