I am implementing android GridviewPager android wear application. with the help of this code sample.
I want to display 2 action buttons, its onClick events, its text, background image. current code is looks like , in round wear emulator
and square emulator
my questions are.
1) How to remove top most black part in round emulator
2) Center image and text in square emulator
3) Perform onClick events on action buttons click
GridPagerAdapter
public class GridPagerAdapter extends FragmentGridPagerAdapter{
private Context mContext;
private ArrayList<GridRow> mRows;
public GridPagerAdapter(Context mContext, FragmentManager fm) {
super(fm);
this.mContext = mContext;
initAdapter();
}
private void initAdapter() {
mRows = new ArrayList<GridRow>();
GridRow row1 = new GridRow();
row1.addPage(new GridPage("", " Add Call", R.drawable.addcall, R.mipmap.ic_launcher));
row1.addPage(new GridPage("", " View Map", R.drawable.view_map, R.mipmap.ic_launcher));
mRows.add(row1);
}
#Override
public Fragment instantiateItem(ViewGroup container, int row, int column) {
Log.d("GridPagerAdapter","in instantiateItem row = "+row+"column = "+column);
return super.instantiateItem(container, row, column);
}
#Override
public Fragment getFragment(int row, int col) {
GridPage page = mRows.get(row).getPage(col);
Log.d("GridPagerAdapter","in getFragment row = "+row+"column = "+col);
CardFragment cardFragment = CardFragment.create(page.getTitle(), page.getText(), page.getIcon());
return cardFragment;
}
#Override
public Drawable getBackgroundForPage(int row, int column) {
GridPage page = mRows.get(row).getPage(column);
return getBackgroundForRow(page.getBackground());
}
#Override
public int getRowCount() {
return mRows.size();
}
#Override
public int getColumnCount(int row) {
return mRows.get(row).getSize();
}
}
Wear Activity
public class WearActivity extends Activity {
private GridViewPager mPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_wear);
mPager = (GridViewPager) findViewById(R.id.gridPager);
mPager.setAdapter(new GridPagerAdapter(this, getFragmentManager()));
}
}
Thanks for help in advance
Finally get the answer
1) Add following code in one of xml (rect,round)
<ImageView
android:id="#+id/imgview"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_marginTop="35dp"
android:layout_gravity="center_horizontal"
android:src="#drawable/card1"/>
<TextView android:id="#+id/text"
android:layout_width="wrap_content"
android:layout_marginTop="10dp"
android:layout_gravity="center_horizontal"
android:layout_height="wrap_content"
android:text="#string/hello_square" />
2) Edit instantiateItem method
#Override
public Object instantiateItem(ViewGroup viewGroup, final int row, final int col) {
final View view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.rect_activity_wear, viewGroup, false);
final TextView textView = (TextView) view.findViewById(R.id.text);
final ImageView imageView = (ImageView) view.findViewById(R.id.imgview);
imageView.setImageResource(carImageIDs[row][col]);
textView.setText(ImageTexts[row][col]);
viewGroup.addView(view);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d("Wear","Image Click row = "+row+"col = "+col);
}
});
textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d("Wear","text Click row = "+row+"col = "+col);
}
});
return view;
}
Hope it helps someone , happy coding
Related
Hi everyone i have created project for survey in area. i have loaded the question in the recycler view where edittext,radiobutton,checkbox,spinner are generated dynamically(there no separate layout files for each) i have used new edittext and used textwatcher to keep the answers dynamically updated in the list so that it can return to mainactivity i.e from adapterclass to activity class. my problem is that the edittext, radiobuttons,etc are getting duplicated but not the question in the textview on scroll up or down or keyboard down after the if there operator performed like enter input inside edittext or change value in spinner then scroll up
note:- the textview is static component the dynamic input are add to linearlayout inside the row layout file that is textview and edittext are both childcomponents of linearlayout based on if case the input type is added as 2nd child of linear layout
Activity.class
mlist=new ArrayList<>();
mlist.clear();
mlist=db.populatequestion();
Log.d("size", String.valueOf(mlist.size()));
Log.d("Question",mlist.get(0).getQuestionType());
mRecyclerView=findViewById(R.id.rvForm);
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
formsadapter =new formsadapter(mlist,this,mRecyclerView);
mRecyclerView.setAdapter(formsadapter);
formsadapter.class
public class formsadapter extends RecyclerView.Adapter<formsadapter.ViewHolder> {
private List<FormQData> mlists;
private List<formanswer> formanswers;
private Context mContext1;
private RecyclerView mRecyclerV1;
public class ViewHolder extends RecyclerView.ViewHolder{
public LinearLayout linearLayout;
public TextView Question;
public View layout;
public ViewHolder(View v) {
super(v);
layout=v;
Question=v.findViewById(R.id.tvQuestion);
linearLayout=v.findViewById(R.id.llform);
formanswers = new ArrayList<>();
}
}
public formsadapter(List<FormQData> myDataset, Context context, RecyclerView recyclerView) {
mlists = myDataset;
mContext1 = context;
mRecyclerV1 = recyclerView;
}
public formsadapter.ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType){
LayoutInflater inflater = LayoutInflater.from(
parent.getContext());
View v =inflater.inflate(R.layout.row_form, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
public void onBindViewHolder(formsadapter.ViewHolder holder, final int position){
final FormQData fb=mlists.get(position);
formanswer fa=new formanswer();
holder.Question.setText(fb.getQuestionContent());
LinearLayout.LayoutParams mainparams1 = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.MATCH_PARENT,1.0f);
mainparams1.gravity= Gravity.RIGHT;
if(fb.getQuestionType().equals("textbox")){
EditText et=new EditText(mContext1);
et.setBackgroundResource(R.drawable.boxwithcircularcoloredborders);
et.setTextColor(mContext1.getResources().getColor(R.color.colorPrimary));
et.setPadding(15,15,15,15);
et.addTextChangedListener(new TextWatcher() {
#Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
#Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
#Override
public void afterTextChanged(Editable editable) {
fa.setQuestionid(fb.getQuestionid());
fa.setAnswer(et.getText().toString());
if(formanswers.contains(fa)){
formanswers.set(formanswers.indexOf(fa),fa);
}
else
formanswers.add(fa);
}
});
holder.linearLayout.addView(et,1);
}
else if(fb.getQuestionType().equals("radiobox")){
RadioGroup rg=new RadioGroup(mContext1);
rg.setOrientation(RadioGroup.HORIZONTAL);
String[] arrOfStr = fb.getQuestionOptions().split(":");
RadioButton[] radiobutton = new RadioButton[arrOfStr.length];
for(int i=0;i<arrOfStr.length;i++){
radiobutton[i]=new RadioButton(mContext1);
radiobutton[i].setText(arrOfStr[i]);
radiobutton[i].setLayoutParams(mainparams1);
radiobutton[i].setBackgroundResource(R.drawable.boxwithcircularcoloredborders);
radiobutton[i].setTextColor(mContext1.getResources().getColor(R.color.colorPrimary));
radiobutton[i].setTypeface(Typeface.DEFAULT_BOLD);
radiobutton[i].setPadding(15,15,15,15);
int finalI = i;
radiobutton[i].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
fa.setQuestionid(fb.getQuestionid());
fa.setAnswer(radiobutton[finalI].getText().toString());
if(formanswers.contains(fa)){
formanswers.set(formanswers.indexOf(fa),fa);
}
else
formanswers.add(fa);
}
});
rg.addView(radiobutton[i],i);
}
holder.linearLayout.addView(rg,1);
}
else if(fb.getQuestionType().equals("checkbox")){
List<String> answer=new ArrayList<>();
RadioGroup rg=new RadioGroup(mContext1);
rg.setOrientation(RadioGroup.HORIZONTAL);
String[] arrOfStr = fb.getQuestionOptions().split(":");
CheckBox[] checkBoxes = new CheckBox[arrOfStr.length];
for(int i=0;i<arrOfStr.length;i++){
checkBoxes[i]=new CheckBox(mContext1);
checkBoxes[i].setText(arrOfStr[i]);
checkBoxes[i].setLayoutParams(mainparams1);
checkBoxes[i].setBackgroundResource(R.drawable.boxwithcircularcoloredborders);
checkBoxes[i].setTextColor(mContext1.getResources().getColor(R.color.colorPrimary));
checkBoxes[i].setTypeface(Typeface.DEFAULT_BOLD);
checkBoxes[i].setPadding(15,15,15,15);
int finalI = i;
checkBoxes[i].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
fa.setQuestionid(fb.getQuestionid());
if(checkBoxes[finalI].isChecked()){
String temp=checkBoxes[finalI].getText().toString();
if(answer.contains(temp)){
answer.set(answer.indexOf(temp),temp);
}else {
answer.add(checkBoxes[finalI].getText().toString());
}
}else{
answer.remove(checkBoxes[finalI].getText().toString());
}
fa.setAnswer(answer.toString());
if(formanswers.contains(fa)){
formanswers.set(formanswers.indexOf(fa),fa);
}
else
formanswers.add(fa);
}
});
rg.addView(checkBoxes[i],i);
}
holder.linearLayout.addView(rg,1);
}
else if(fb.getQuestionType().equals("dropdown")){
Spinner spinner=new Spinner(mContext1);
fa.setQuestionid(fb.getQuestionid());
List<String> arrOfStr=new ArrayList<>(Arrays.asList(fb.getQuestionOptions().split(":")));
arrOfStr.add(0,"Select A Option");
ArrayAdapter<String> spinnerAdapter=new ArrayAdapter<>(mContext1,R.layout.row_dropdownsinglecelltv,R.id.tvsinglecell2,arrOfStr);
spinnerAdapter.setDropDownViewResource(R.layout.row_dropdownsinglecelltv);
spinner.setPopupBackgroundDrawable(mContext1.getResources().getDrawable(R.drawable.boxcircularcorner));
spinner.setAdapter(spinnerAdapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
String spinnerValue=String.valueOf(adapterView.getSelectedItem());
if (!spinnerValue.equals("Select A Option")){
//Log.d("value","upload");
fa.setAnswer(spinnerValue);
if(formanswers.contains(fa))
formanswers.set(formanswers.indexOf(fa),fa);
else
formanswers.add(fa);
}else{
if(formanswers.contains(fa))
formanswers.remove(fa);
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
holder.linearLayout.addView(spinner,1);
}
else {
TextView et=new TextView(mContext1);
et.setText("invalid question type");
holder.linearLayout.addView(et,1);
}
}
public int getItemCount(){
return mlists.size();
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
return position;
}
public List<formanswer> formanswers(){
return formanswers;
}
}
row_form.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:padding="10dp"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:id="#+id/llform"
android:background="#drawable/boxwithcoloredborder"
android:layout_width="match_parent"
android:padding="15dp"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/tvQuestion"
android:padding="5dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#color/colorPrimary"
android:textStyle="bold"
android:text="TextView" />
</LinearLayout>
</LinearLayout>
here is the sample video
https://imgur.com/a/hi3Vb5a
i have found the solution it seems the problem is entirely different. The problem is that the recycler view is not getting recycled properly its has viewCachesize which needs to be increased to list size
you can check if your recyclerview is getting recycled or not using
#Override
public void onViewRecycled(#NonNull formsadapter.ViewHolder holder) {
Log.d("recyclerview","recyclerview is recycled");
}
if the log is being appeared then you solve this issue adding
holder.setIsRecyclable(false);
in the onbindviewholder or adding
mRecyclerView.setItemViewCacheSize(mlist.size()+1);
in the main activity itself
Evidently just use the listview itself instead of recyclerview then these lines dont need to be added
links:-
RecyclerView not recycling views if the view count is small
How can I detect recycling from within a recyclerView adapter, so I can perform an action before it gets recycled?
So I am trying to make my cards clickable and as they are clicked it opens a new activity (not implemented in the code below though), here is my code:
For Interface
import android.view.View;
public interface ClickListener {
public void itemClicked(View view , int position);
}
For Adapter:
public class RVAdapter extends RecyclerView.Adapter<RVAdapter.SensorViewHolder> {
private ClickListener clicklistener = null;
List<SensorData> sensors;
RVAdapter(List<SensorData> sensors) {
this.sensors = sensors;
}
public class SensorViewHolder extends RecyclerView.ViewHolder {
CardView cv;
TextView sensorName;
TextView sensorDesc;
ImageView sensorPhoto;
private LinearLayout main;
SensorViewHolder(final View itemView) {
super(itemView);
cv = (CardView) itemView.findViewById(R.id.cv);
sensorName = (TextView) itemView.findViewById(R.id.sensor_name);
sensorDesc = (TextView) itemView.findViewById(R.id.sensor_desc);
sensorPhoto = (ImageView) itemView.findViewById(R.id.sensor_photo);
main = (LinearLayout) itemView.findViewById(R.id.main);
main.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(itemView.getContext(), "Position:" + Integer.toString(getPosition()), Toast.LENGTH_SHORT).show();
if(clicklistener != null){
clicklistener.itemClicked(v, getAdapterPosition());
}
}
});
}
}
public void setClickListener(ClickListener clickListener){
this.clicklistener = clickListener;
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
#Override
public SensorViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item, viewGroup, false);
SensorViewHolder pvh = new SensorViewHolder(v);
return pvh;
}
#Override
public void onBindViewHolder(SensorViewHolder SensorViewHolder, int i) {
SensorViewHolder.sensorName.setText(sensors.get(i).name);
SensorViewHolder.sensorDesc.setText(sensors.get(i).descriptor);
SensorViewHolder.sensorPhoto.setImageResource(sensors.get(i).iconID);
}
#Override
public int getItemCount() {
return sensors.size();
}
}
and here is the code for MainActivity:
public class MainActivity extends AppCompatActivity {
private List<SensorData> sensorData;
private RecyclerView rv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Find the recycler view for the <code>
rv = (RecyclerView) findViewById(R.id.rv);
//Initialising a linear layout manager
final LinearLayoutManager llm = new LinearLayoutManager(this);
rv.setLayoutManager(llm);
rv.setHasFixedSize(true);
initializeData();
initializeAdapter();
rv.setClickListener(this);
}
private void initializeData() {
sensorData = new ArrayList<>();
sensorData.add(new SensorData("Accelerometer", "Measures the acceleration of a moving or vibrating body.", R.mipmap.ic_accl));
sensorData.add(new SensorData("GPS Sensor", "Provides real-time user location and time information.", R.mipmap.ic_gps));
sensorData.add(new SensorData("Proximity Sensor", "Provides ambient light and proximity sensing.", R.mipmap.ic_als));
}
private void initializeAdapter() {
RVAdapter adapter = new RVAdapter(sensorData);
rv.setAdapter(adapter);
}
}
And yet it seems I cannot access setClickListener. I must mention I am quite a beginner in this.
Where have I mistaken? Is this the correct way to implement clicks on a card or I am missing something?
Also here is the MainActivity XML if needed.
<?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:padding="16dp"
android:id="#+id/main">
<android.support.v7.widget.RecyclerView
android:layout_height="match_parent"
android:layout_width="match_parent"
android:id="#+id/rv">
</android.support.v7.widget.RecyclerView>
</LinearLayout>
and items.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/cv"
app:cardUseCompatPadding="true">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="16dp">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/sensor_photo"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginRight="16dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/sensor_name"
android:layout_toRightOf="#+id/sensor_photo"
android:layout_alignParentTop="true"
android:textSize="30sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/sensor_desc"
android:layout_toRightOf="#+id/sensor_photo"
android:layout_below="#+id/sensor_name" />
</RelativeLayout>
</android.support.v7.widget.CardView>
EDIT: Just to avoid confusion, **I want the use to be able to click the cards and go to a new activity. ** How can I implement that in the simplest possible way? I am really confused on how to do it in the RecyclerView.
Thanks a lot and regards.
Since there is a difference between the old ListView and the new RecyclerView component, I have a reusable piece of code that I use to handle click events (both regular clicks and LongClicks):
public class RecyclerItemClickListener implements RecyclerView.OnItemTouchListener {
#SuppressWarnings("CanBeFinal")
private GestureDetector mGestureDetector;
#SuppressWarnings("CanBeFinal")
private OnItemClickListener mListener;
public interface OnItemClickListener {
void onItemClick(View view, int position);
void onItemLongClick(View view, int position);
}
public RecyclerItemClickListener(Context context, final RecyclerView recyclerView, OnItemClickListener listener)
{
mListener = listener;
mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener()
{
#Override
public boolean onSingleTapUp(MotionEvent e)
{
return true;
}
#Override
public void onLongPress(MotionEvent e)
{
View childView = recyclerView.findChildViewUnder(e.getX(), e.getY());
if(childView != null && mListener != null)
{
mListener.onItemLongClick(childView, recyclerView.getChildAdapterPosition(childView));
}
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e)
{
View childView = view.findChildViewUnder(e.getX(), e.getY());
if(childView != null && mListener != null && mGestureDetector.onTouchEvent(e))
{
mListener.onItemClick(childView, view.getChildAdapterPosition(childView));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView view, MotionEvent motionEvent){}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
Then simply do this in your activity or fragment where you want to handle click events:
mRecyclerView.addOnItemTouchListener(new RecyclerItemClickListener(this, mRecyclerView, new RecyclerItemClickListener
.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
//start new activity here
}
#Override
public void onItemLongClick(View view, int position) {
}
}));
That should be the easiest way to do it!
I hope this helps you! Good luck and happy coding!
Basically you need to set the listener in the Viewholder
public class SensorViewHolder extends RecyclerView.ViewHolder {
CardView cv;
TextView sensorName;
TextView sensorDesc;
ImageView sensorPhoto;
private LinearLayout main;
SensorViewHolder(final View itemView) {
super(itemView);
cv = (CardView) itemView.findViewById(R.id.cv);
//Add the following line below
cv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//The intent firing goes here
}
});
sensorName = (TextView) itemView.findViewById(R.id.sensor_name);
sensorDesc = (TextView) itemView.findViewById(R.id.sensor_desc);
sensorPhoto = (ImageView) itemView.findViewById(R.id.sensor_photo);
main = (LinearLayout) itemView.findViewById(R.id.main);
main.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(itemView.getContext(), "Position:" + Integer.toString(getPosition()), Toast.LENGTH_SHORT).show();
if(clicklistener != null){
clicklistener.itemClicked(v, getAdapterPosition());
}
}
});
}
}
Hope it helps.
To fix the compiler error, the correct way to set a OnClickListener is with
rv.setOnClickListener()
Note that the error is because you are missing the word On. Generally, you should use autocomplete in Android Studio to help avoid these types of issues. If autocomplete doesn't pop up automatically, you can push Ctrl-Space to get it.
As a side note, you can build your project by clicking Build -> Make Project in the main menu. This will give a window with the error messages where you can copy and paste more easily than the usual error balloons.
first of all set tag for your card in onBindViewHolder:
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.cv.setTag(position);
}
then add on click listener for your card in your view holder in adapter:
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public CardLayout cv;
public ViewHolder(View itemView) {
super(itemView);
cv = (CardView) itemView.findViewById(Rid.cv);
cv.setOnClickListener(this);
}
#Override
public void onClick(View v) {
//for find item that hold in list
int postition = (Integer) v.getTag();
...
}
In your findViewById you are casting the view to a RecyclerView and therefore you are referring the standard RecyclerView implementation of the Android framework. So this would never work.
The next thing is you are trying to set a listener to the RecyclerView but define the setListener method inside your adapter.
So what you should do is to either get a reference to your adapter via:
((RvAdapter) rv.getAdapter()).setClickListener();
after setting it or even better set the listener before you call
rv.setAdapter()
via
RvAdapter adapter = new RvAdapter();
adapter.setClickListener(listener)
I'm fairly new to Android programming, and I'm trying to design an app where when I swipe through several images on a ViewPager that takes up some of the screen, other elements of that same activity/screen will change with it without necessarily 'scrolling' horizontally like the ViewPager does. My problem is that I can't find a way to identify which image in the ViewPager is the 'current' one outside of the ViewPager.
I tried to create a getter for grabbing the position from instantiateItem method, but no luck - because I assume it simply creates everything once, not updating it again, so when I swipe nothing will happen. Also, I realize that my dieValue variable doesn't do anything - but it's meant to serve as an example of what I want to accomplish. The dieValue variable would change based on which image was the current one.
CustomSwipeAdapter.java
public class CustomSwipeAdapter extends PagerAdapter {
private Context ctx;
public int[] image_resources = {R.drawable.d20, R.drawable.d8, R.drawable.d6};
public CustomSwipeAdapter(Context ctx) {
this.ctx = ctx;
}
#Override
public int getCount() {
return image_resources.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
LayoutInflater layoutInflater = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View item_view = layoutInflater.inflate(R.layout.swipe_layout, container, false);
ImageView imageView = (ImageView) item_view.findViewById(R.id.dieImageView);
imageView.setImageResource(image_resources[position]);
TextView textView = (TextView) item_view.findViewById(R.id.dieValueTop);
if (position == 0) { textView.setText(R.string.d20Label); }
if (position == 1) { textView.setText(R.string.d8Label); }
if (position == 2) { textView.setText(R.string.d6Label); }
container.addView(item_view);
return item_view;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((LinearLayout) object);
}
}
DiceRollerActivity.java
public class DiceRollerActivity extends Activity implements View.OnClickListener {
ViewPager viewPager;
CustomSwipeAdapter adapter;
private int dieValue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dice_roller);
viewPager = (ViewPager) findViewById(R.id.dieViewPager);
adapter = new CustomSwipeAdapter(this);
viewPager.setAdapter(adapter);
Button RollDieButton = (Button) findViewById(R.id.rollDieButton);
RollDieButton.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.rollDieButton:
Random rand = new Random();
int random = rand.nextInt(dieValue) + 1;
setDieResults(random);
}
}
// Prints the results of the die roll to the results log
private void setDieResults(int random) {
TextView dieResults = (TextView) findViewById(R.id.dieResultsLabel);
if (random == dieValue) {
dieResults.setText(getString(R.string.YouRolledLabel) + random + getString(R.string.criticalHit));
} else if (random == dieValue) {
dieResults.setText(getString(R.string.YouRolledLabel) + random + getString(R.string.criticalMiss));
}else{
dieResults.setText(getString(R.string.YouRolledLabel) + random);
}
}
}
Create a method inside your CustomSwipeAdapter
public int getCurrentImageResource(int currentPosition){
return image_resources[currentPosition];
}
To access to the current image call this method passing current position with viewPager.getCurrentItem() like this
adapter.getCurrentImageResource(viewPager.getCurrentItem());
Hope this helps!
You could use
viewPager.getCurrentItem();
on your DiceRollerActivity.class to get the current position.
Then, to get the image a better approach would be to have the image array on your DiceRollerActivity.class and pass it onto the CustomSwipeAdapter constructor.
I am using view pager in my activity.I created views for 7 pages. Now i want to access page view inside my activity. I am getting data as blank.
In Activity
public class ActivitySingleEntry extends Activity implements OnClickListener {
private ViewPager mPager;
private FixedTabsView mFixedTabs;
private ExamplePagerAdapter mPagerAdapter;
private TabsAdapter mFixedTabsAdapter;
private EditText edtFieldName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fixed_tabs);
initViewPager(7, 0xFFFFFFFF, 0xFF000000);
mFixedTabs = (FixedTabsView) findViewById(R.id.fixed_tabs);
mFixedTabsAdapter = new FixedTabsAdapter(this);
mFixedTabs.setAdapter(mFixedTabsAdapter);
mFixedTabs.setViewPager(mPager);
}
private void initViewPager(int pageCount, int backgroundColor, int textColor) {
mPager = (ViewPager) findViewById(R.id.pager);
mPagerAdapter = new ExamplePagerAdapter(this, pageCount,
backgroundColor, textColor);
mPager.setAdapter(mPagerAdapter);
mPager.setCurrentItem(1);
mPager.setPageMargin(5);
}
#Override
public void onClick(View v) {
// LinearLayout lin=(LinearLayout) mPager.getChildAt(mPager.getCurrentItem());
// edtFieldName=(EditText) lin.findViewById(R.id.edtFieldName);
// Log.d("test", "From get child:"+edtFieldName.getText().toString()+":");
Log.d("test", "Current Page:"+mPager.getCurrentItem());
LinearLayout linearLayout=(LinearLayout) mPager.findViewWithTag("lin"+mPager.getCurrentItem());
edtFieldName=(EditText) linearLayout.findViewById(R.id.edtFieldName);
edtFieldName=(EditText) findViewById(R.id.edtFieldName);
if (edtFieldName==null) {
ShowToast.makeToast(getApplicationContext(), "Edt null");
}else
ShowToast.makeToast(getApplicationContext(),
"Data saved " + edtFieldName.getText().toString() + ":"
+ mPager.getCurrentItem());
}
}
My PageAdaper
public class ExamplePagerAdapter extends PagerAdapter {
protected transient Activity mContext;
private int mLength = 0;
private int mBackgroundColor = 0xFFFFFFFF;
private int mTextColor = 0xFF000000;
private String[] mData = { "Temperature", "Sugar", "BP", "Field 4",
"Field 5", "Field 6", "Field 7" };
public ExamplePagerAdapter(Activity context, int length,
int backgroundColor, int textColor) {
mContext = context;
mLength = length;
mBackgroundColor = backgroundColor;
mTextColor = textColor;
}
#Override
public int getCount() {
return mLength;
}
#Override
public Object instantiateItem(View container, int position) {
LinearLayout linearLayout = (LinearLayout) View.inflate(mContext,
R.layout.activity_single_entry, null);
TextView txtFieldName = (TextView) linearLayout
.findViewById(R.id.txtFieldName);
EditText edtFieldName = (EditText) linearLayout
.findViewById(R.id.edtFieldName);
String filedName = mData[position];
txtFieldName.setText(filedName);
edtFieldName.setHint("Please enter " + filedName);
edtFieldName.setInputType(InputType.TYPE_CLASS_TEXT);
if (filedName.equals("Temperature")) {
edtFieldName.setInputType(InputType.TYPE_CLASS_NUMBER);
} else if (filedName.equals("Sugar")) {
edtFieldName.setInputType(InputType.TYPE_CLASS_NUMBER);
} else if (filedName.equals("BP")) {
edtFieldName.setInputType(InputType.TYPE_CLASS_NUMBER);
}
edtFieldName.setTag("edt");
((ViewPager) container).addView(linearLayout, 0);
linearLayout.setTag("lin"+position);
Log.d("test", "Adapter creating item:"+position );
return linearLayout;
}
#Override
public void destroyItem(View container, int position, Object view) {
((ViewPager) container).removeView((View) view);
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((View) object);
}
#Override
public void finishUpdate(View container) {
}
#Override
public void restoreState(Parcelable state, ClassLoader loader) {
}
#Override
public Parcelable saveState() {
return null;
}
#Override
public void startUpdate(View container) {
}
}
In R.layout.activity_single_entry xml i have edittext and button with onclick.
MYXml
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/txtFieldName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
<EditText
android:id="#+id/edtFieldName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_weight="1"
android:hint="Please enter field value" />
</LinearLayout>
<Button
android:id="#+id/btnSave"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Save"
android:layout_margin="20dp"
android:onClick="onClick"
/>
</LinearLayout>
If i used inside pageadapter
#Override
public int getItemPosition(Object object) {
// TODO Auto-generated method stub
return POSITION_NONE;
}
OnClick of button i want to access data from edit text.
I able to get value for first page.Not for all.
firstm you setTag():
linearLayout.setTag("lin"+position);
where position is in <0..numPages-1>
but read it:
LinearLayout linearLayout=(LinearLayout) mPager.findViewWithTag("lin"+mPager.getCurrentItem());
is findViewWithTag returning null everywhere or only on the last page?
mPager.getCurrentItem() returns 0 if it is first page so there is no need to add +1 while reading
In page adapter i am using single view in each page so its refers to only first item.If i tried to get view for page its giving me only first object so i applied distinct id for edit text in each page.
In page adapter
#Override
public Object instantiateItem(View container, int position) {
LinearLayout linearLayout = (LinearLayout) View.inflate(mContext,
R.layout.activity_single_entry, null);
TextView txtFieldName = (TextView) linearLayout
.findViewById(R.id.txtFieldName);
EditText edtFieldName = (EditText) linearLayout
.findViewById(R.id.edtFieldName);
***edtFieldName.setId(position);***
String filedName = mData[position];
txtFieldName.setText(filedName);
edtFieldName.setHint("Please enter " + filedName);
edtFieldName.setInputType(InputType.TYPE_CLASS_TEXT);
if (filedName.equals("Temperature")) {
edtFieldName.setInputType(InputType.TYPE_CLASS_NUMBER);
} else if (filedName.equals("Sugar")) {
edtFieldName.setInputType(InputType.TYPE_CLASS_NUMBER);
} else if (filedName.equals("BP")) {
edtFieldName.setInputType(InputType.TYPE_CLASS_NUMBER);
}
edtFieldName.setTag("edt"+position);
((ViewPager) container).addView(linearLayout, 0);
mItems.add(linearLayout);
linearLayout.setTag("lin"+position);
Log.d("test", "Adapter creating item:"+position );
return linearLayout;
}
Its working now
A quick solution would be to keep a List in your ExamplePagerAdapter and add to it after your addView() call. Then you could implement a public function such as getItemAtPosition(int position) that returns the LinearLayout at that page of the ViewPager. Then you can run findViewById(R.id.edtFieldName) on that linear layout in your Activity. In code:
In your ExamplePagerAdapter, add a private object:
List<LinearLayout> mItems;
add in your constructor:
mItems = new Vector<LinearLayout>();
add in instantiateItem():
((ViewPager) container).addView(linearLayout, 0);
mItems.add(linearLayout);
then add a method:
public LinearLayout getItemAtPosition(int position) {
return mItems.get(position);
}
Then use that method in your Activity. Hope it's what you were looking for.
I have a list view in left of the screen and on click of the item i want to update a text on the right half of the screen, what i want to do here is that to move the clicked item in center of the listview. Like if the item is on top and i click on it it automatically moves to the center of the list view, how I can do this? Any kind of help will be appreciated.
I have a listview in which 7 items are visible and on startup 4th item will be selected as this is in center of the visible items in listview and if there are n items and whichever item is selected by user will be in center of the visible items in listview. Like i have 10 items and on start 4th is selected and when user selects the 3rd item, nth item from listview should come to index zero and and 3rd will come to position 4. Similarly for every other selected item? Can any one provide a code snippet for this?
Change items order in ListView source Array and then call notifyDataSetChanged() in ListView Adapter
EDIT: Code sample
public class ListAdapter extends BaseAdapter{
private Activity activity;
private ArrayList<ListRowObject> listItems;
public ListAdapter(Activity activity){
this.activity = activity;
listItems = new ArrayList<ListRowObject>();
}
public void addItem(ListRowObject item){
listItems.add(item);
notifyDataSetChanged();
}
public void addItems(ArrayList<ListRowObject> items){
listItems = items;
notifyDataSetChanged();
}
public void clear(){
listItems = null;
listItems = new ArrayList<ListRowObject>();
notifyDataSetChanged();
}
#Override
public int getCount() {
return listItems.size();
}
#Override
public Object getItem(int position) {
return listItems.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup viewGroup) {
ViewHolder holder;
if(convertView == null){
holder = new ViewHolder();
convertView = activity.getLayoutInflater().inflate(R.layout.list_row, null);
holder.text = (TextView) convertView.findViewById(R.id.text);
holder.bgLayout = (LinearLayout) convertView.findViewById(R.id.bgLayout);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
ListRowObject row = listItems.get(position);
if(row.isSelected())
holder.bgLayout.setBackgroundColor(Color.GRAY);
else
holder.bgLayout.setBackgroundColor(Color.WHITE);
holder.text.setText(row.getText());
return convertView;
}
}
//--------
public class ListRowObject {
private String text;
private int positionInList;
private boolean isSelected;
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public int getPositionInList() {
return positionInList;
}
public void setPositionInList(int positionInList) {
this.positionInList = positionInList;
}
public boolean isSelected() {
return isSelected;
}
public void setSelected(boolean selected) {
isSelected = selected;
}
}
//------
public class Main extends Activity {
private ListView listView;
private ListAdapter adapter;
private Activity activity;
private ArrayList<ListRowObject> items;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
activity = this;
initializeFormViews();
initializeOnClickEvents();
fillList();
}
private void initializeFormViews(){
listView = (ListView) findViewById(R.id.listView);
}
private void initializeOnClickEvents(){
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
Toast.makeText(activity, "Pressed " +position, Toast.LENGTH_SHORT).show();
// unselect all rows
for(ListRowObject item : items){
item.setSelected(false);
}
int first = adapterView.getFirstVisiblePosition();
int last = adapterView.getLastVisiblePosition();
int centerPosition = (first + last) / 2;
// change bg for centerPosition row
adapterView.getChildAt(centerPosition).findViewById(R.id.bgLayout).setBackgroundColor(Color.GRAY);
changeItems(position, centerPosition);
}
});
}
private void changeItems(int pressedPosition, int centerPosition){
ListRowObject centerRow = items.get(centerPosition);
ListRowObject pressedRow = items.get(pressedPosition);
pressedRow.setSelected(true);
centerRow.setSelected(false);
items.remove(centerPosition);
items.add(centerPosition, pressedRow);
items.remove(pressedPosition);
items.add(pressedPosition, centerRow);
adapter.clear();
adapter.addItems(items);
}
private void fillList(){
adapter = new ListAdapter(activity);
items = new ArrayList<ListRowObject>();
items = getItems();
for(ListRowObject item : items){
adapter.addItem(item);
}
listView.setAdapter(adapter);
}
private ArrayList<ListRowObject> getItems(){
ArrayList<ListRowObject> result = new ArrayList<ListRowObject>();
for(int i = 0; i < 15; i++){
ListRowObject object = new ListRowObject();
object.setPositionInList(i);
object.setText("Item #" + i);
if(i != 4)
object.setSelected(false);
else
object.setSelected(true);
result.add(object);
}
return result;
}
}
//------
public class ViewHolder {
public TextView text;
public LinearLayout bgLayout;
}
list_row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="50dp"
android:id="#+id/bgLayout">
<TextView
android:layout_width="match_parent"
android:layout_height="50dp"
android:id="#+id/text"
android:textColor="#000000"
android:textSize="24dp"
android:gravity="center"/>
</LinearLayout>
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/listView"/>
</LinearLayout>
when you create ArrayAdapter for your listview you send a ListArray to it.when you want change content .you only change this listArray then when click your item you can change ListArray and call notifyDataSetChanged(); method your adapter.