displaying listview info into different textviews android - android

I want to display each item that is clicked into a different textView. I have each click displaying in the same textView now but i would like on each click for the data to be displayed in a new textView. Any Ideas? here is what i have so far:
ExercisesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
private String result;
TextView Exercise1TextView = (TextView) findViewById(R.id.Exercise1TextView);
TextView Exercise2TextView = (TextView) findViewById(R.id.Exercise2TextView);
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String Exercise = String.valueOf(adapterView.getItemAtPosition(i));
result = (Exercise1TextView.getText().toString() + "\n" + Exercise);
Exercise1TextView.setText(result);
}
});

The answer to your question is very simple, you will need to create new TextViews dynamically and setText to them. This is how you should proceed. Add a linearlayout in your main layout above or below your listview where ever you desire, just like below.
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="#+id/main_layout"
/>
In your Activity initialize this linearlayout
public class MainActivity extends Activity {
private LinearLayout mainLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(....);
setContentView(....);
this.mainLayout = (LinearLayout) findViewById(R.id.main_layout);
}
}
Now in your onItemClick do like this.
TextView tv = new TextView(getApplicationContext());
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
tv.setTextColor(Color.BLACK);
tv.setText(result);
mainLayout.addView(tv, params);

Create an array of TextViews like that:
View[] myViews = {textView1, textView2, ....};
And call them inside onItemClick()
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
k = myViews.length < i ? myViews.length -1 : i; //or use your logic
String Exercise = String.valueOf(adapterView.getItemAtPosition(i));
result = (Exercise1TextView.getText().toString() + "\n" + Exercise);
myViews[k].setText(result);
}

Related

How to add a variable number of TextViews and EditViews in activity

I'm currently trying to add a user-defined number of TextViews and EditText to an activity, but can't seem to do it other than hard-coding it by creating a variety of different activities.
The objective of this activity is to take the names of the players, the number of which is relayed by the intent extra from the preceding activity.
I'm trying to add both a TextView saying "Player X: " and an EditText to type the name of the player for each player
I know from this post: How to create a variable number of textviews in android that I have to do this programmatically, however, it does not seem to work for me (the activity remains blank when tested)
I have tried creating a temp LinearLayout to which I add the two views in a for(), still nothing.
Any ideas? Am I on the right track?
Best regards
[EDIT] Code is here :
public class players extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_players);
Bundle extras = new Bundle();
final int numPlayers = extras.getInt("num");
final LinearLayout myLayout = findViewById(R.id.lin_Re);
final ArrayList<Player> players = new ArrayList<>();
int size = numPlayers; // total number of TextViews to add
TextView[] tv = new TextView[size];
TextView temp;
EditText[] et = new EditText[size];
EditText temp2;
LinearLayout temp3;
for (int i = 0; i < size; i++)
{
temp = new TextView(this);
temp2 = new EditText(this);
temp3 = new LinearLayout(this);
temp.setText("Player " + i + " : "); //arbitrary task
// add the textview to the linearlayout
temp3.addView(temp);
temp3.addView(temp2);
tv[i] = temp;
et[i] = temp2;
myLayout.addView(temp3);
}
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
android:id="#+id/lin_Re">
</LinearLayout>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/b_send"/>
</LinearLayout>
There is 2 way to achieve this:
1. Use a RecyclerView [Recommended]
2. Add TextView and EditText ( which is nested in a Horizontal LinearLayout) into a Vertical LinearLayout nested in a ScrollView programmatically
The first solution I describe below is quite simple if you're familiar with RecyclerView or ListView, the second solution (your current track) is a bit tricky but still achievable.
Solution 1:
MainActivity
public class MainActivity extends AppCompatActivity {
RecyclerView mPlayerList;
List<String> mPlayerNames;
PlayerAdapter mAdapter;
EditText mInput;
Button mCreateButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mPlayerNames = new ArrayList<>();
// setup recycler view
mPlayerList = findViewById(R.id.player_list);
mPlayerList.setLayoutManager(new LinearLayoutManager(this));
mAdapter = new PlayerAdapter();
mPlayerList.setAdapter(mAdapter);
// setup input EditText
mInput = findViewById(R.id.input);
// setup Create button
mCreateButton = findViewById(R.id.create_button);
mCreateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// clear old player names
mPlayerNames.clear();
// read user input: number of player:
String input = mInput.getText().toString();
int numberOfPlayer;
try {
numberOfPlayer = Integer.parseInt(input);
} catch (NumberFormatException e) {
Toast.makeText(MainActivity.this, "Invalid input!!!", Toast.LENGTH_SHORT).show();
return;
}
for (int i = 0; i < numberOfPlayer; ++i) {
mPlayerNames.add("Player #" + (i + 1));
}
// make change on recycler view
mAdapter.notifyDataSetChanged();
// dismiss keyboard
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(mInput.getWindowToken(), 0);
}
});
}
private class PlayerAdapter extends RecyclerView.Adapter<PlayerAdapter.PlayerHolder> {
#Override
public PlayerHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(MainActivity.this).inflate(R.layout.item_layout, parent, false);
return new PlayerHolder(v);
}
#Override
public void onBindViewHolder(PlayerHolder holder, int position) {
holder.bind(mPlayerNames.get(position));
}
#Override
public int getItemCount() {
return mPlayerNames.size();
}
public class PlayerHolder extends RecyclerView.ViewHolder {
TextView mPlayerLabel;
EditText mPlayerName;
public PlayerHolder(View itemView) {
super(itemView);
mPlayerLabel = itemView.findViewById(R.id.player_label);
mPlayerName = itemView.findViewById(R.id.player_name);
}
public void bind(String playerName) {
mPlayerLabel.setText(playerName);
mPlayerName.setHint("Name of " + playerName);
}
}
}
}
The sample project can be found here:
https://github.com/raiytu4/stackcase004

how to display text view without bracket

I have an OnItemClick(), after that I wanted to get the ItemClicked name's and display it in a TextView.I do it normally, but the problem is that I get the ItemClicked name's inside a bracket! How do I avoid this?Here is the output:
{titre=hello}
I want only in my TextView:
hello.
Here is the code:
public void onItemClick(AdapterView<?> parent, View view, int position, long id ) {
displayTextViewTitle = (TextView)findViewById(R.id.text_view_title);
Object item = parent.getItemAtPosition(position);
String value = item.toString();
displayTextViewTitle.setText(String.valueOf(value));
}
Try this :
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
TextView displayTextViewTitle = (TextView) findViewById(R.id.textView1);
TextView item = (TextView) parent.getItemAtPosition(position);
String value = item.getText();
displayTextViewTitle.setText(value);
}
or even better try :
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
TextView displayTextViewTitle = (TextView) findViewById(R.id.textView1);
ListView lv = (ListView) findViewById(yourListViewName);
String value = lv.get(position).tostring();
displayTextViewTitle.setText(value);
}
If you are getting your String {titre=hello} like this after click on ListView. then you should use this:
String[] no = item.split("=");
String m = no[0];
String k = no[1];
String name = k.substring(0, k.length() - 1);
name is your final result String .
value is already a String, you don't have to use String.valueOf(value).
The listener method works fine, check this:
public class SplashActivity extends Activity implements OnItemClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
ListView lv = (ListView)findViewById(R.id.lv);
ArrayList<String> members = new ArrayList<String>();
members.add("titre=hello");
members.add("world");
ArrayAdapter s = new ArrayAdapter(this, android.R.layout.simple_list_item_1, members);
lv.setAdapter(s);
lv.setOnItemClickListener(this);
}
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
TextView displayTextViewTitle = (TextView) findViewById(R.id.textView1);
Object item = parent.getItemAtPosition(position);
String value = item.toString();
displayTextViewTitle.setText(String.valueOf(value));
}
}
Recheck the values inside your listview, the problem might be there

Dynamic data loading on custom List-view with background container

I am totally confuse with my image list view.
I want to display 2 video poster and text view in a single row with background container ( check attach image of train)
This is single cell of vertical List view.
Depending on number of videos i have to display vertical list view but each row contain 2 video poster and text view at side of it video with train Engine image at start or end vice versa of row number.
To achieve this UI i write a custom adaptor in which i manage to display train wagon with related image-view by using relative layout.
but how can i manage on-click listener on particular item (particular video in row) on single row.and how can i add train image at start or end of each row
here is output of my code.
Here is my code
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.main);
final Context context = CustomAdapterExample.this;
ListView ls2 = new ListView(context);
// clear previous results in the LV
ls2.setAdapter(null);
// populate
ArrayList<Device> videos = new ArrayList<Device>();
Device my_video;
for (int i=0;i<05;i++) {
my_video = new Device("video link","Video id");
videos.add(my_video);
}
CustomAdapter lvAdapter = new CustomAdapter(context, videos);
ls2.setAdapter(lvAdapter);
ls2.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> arg0, View arg1,int arg2, long arg3)
{
Toast.makeText(getBaseContext(), "You clicked on "+arg2, Toast.LENGTH_LONG).show();
}
});
setContentView(ls2);
}
And here is adaptor
class CustomAdapterView extends LinearLayout {
public CustomAdapterView(Context context, Device device)
{
super( context );
//container is a horizontal layer
setOrientation(LinearLayout.HORIZONTAL);
setPadding(0, 6, 0, 6);
LinearLayout Mainview = new LinearLayout(context);
LinearLayout.LayoutParams Cellparams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
Mainview.setLayoutParams(Cellparams);
ImageView firstImageContainer = new ImageView(context);
ImageView trackImage = new ImageView(context);
ImageView VideoViewContainer = new ImageView(context);
TextView firsttext= new TextView(context);
firsttext.setText("Testing of app");
firsttext.setTextColor(Color.RED);
firstImageContainer.setBackgroundResource(R.drawable.wagon);
VideoViewContainer.setBackgroundResource(R.drawable.video);
RelativeLayout layout = new RelativeLayout(context);
RelativeLayout.LayoutParams firstContainerParams = new RelativeLayout.LayoutParams(160, 80);
layout.setLayoutParams(firstContainerParams);
trackImage.setBackgroundResource(R.drawable.line);
RelativeLayout.LayoutParams trackRules = new RelativeLayout.LayoutParams(755,5);
trackRules.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
RelativeLayout.LayoutParams firstImageContainerParams = new RelativeLayout.LayoutParams(140, 90);
RelativeLayout.LayoutParams VideoViewContainerParams = new RelativeLayout.LayoutParams(70,60);
VideoViewContainerParams.addRule(RelativeLayout.CENTER_VERTICAL);
VideoViewContainerParams.setMargins(5, 0, 0, 0);
layout.addView(firstImageContainer, firstImageContainerParams);
layout.addView(VideoViewContainer, VideoViewContainerParams);
layout.addView(trackImage, trackRules);
ImageView secondImageContainer = new ImageView(context);
ImageView secondtrackImage = new ImageView(context);
ImageView secondVideoViewContainer = new ImageView(context);
secondImageContainer.setBackgroundResource(R.drawable.wagon);
secondVideoViewContainer.setBackgroundResource(R.drawable.video);
RelativeLayout secondLayout = new RelativeLayout(context);
RelativeLayout.LayoutParams secondContainerParams = new RelativeLayout.LayoutParams(160, 80);
secondLayout.setLayoutParams(firstContainerParams);
secondtrackImage.setBackgroundResource(R.drawable.line);
RelativeLayout.LayoutParams secondtrackRules = new RelativeLayout.LayoutParams(755,5);
trackRules.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
RelativeLayout.LayoutParams secondImageContainerParams = new RelativeLayout.LayoutParams(140, 90);
RelativeLayout.LayoutParams secondVideoViewContainerParams = new RelativeLayout.LayoutParams(70,60);
secondVideoViewContainerParams.addRule(RelativeLayout.CENTER_VERTICAL);
secondVideoViewContainerParams.setMargins(5, 0, 0, 0);
secondLayout.addView(secondImageContainer, secondImageContainerParams);
secondLayout.addView(secondVideoViewContainer, secondVideoViewContainerParams);
secondLayout.addView(secondtrackImage, secondtrackRules);
firstContainerParams.addRule(RelativeLayout.ALIGN_LEFT);
secondImageContainerParams.addRule(RelativeLayout.ALIGN_RIGHT);
Mainview.addView(layout,firstContainerParams);
Mainview.addView(secondLayout,secondContainerParams);
addView(Mainview);
}
}
public class CustomAdapter extends BaseAdapter /*implements OnClickListener*/ {
public static final String LOG_TAG = "BI::CA";
private Context context;
private List<videoData> videolist;
public CustomAdapter(Context context, List<Device> videolist ) {
this.context = context;
this.videolist = videolist;
}
public int getCount() {
return videolist.size();
}
public Object getItem(int position) {
return videolist.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent)
{
Device device = videolist.get(position);
View v = new CustomAdapterView(this.context, device );
return v;
}
}
If my implementation is wrong than please suggest me some guidance.
gallery is deprecated in API 17 i can't use it.
Is it possible to crate such Ui by using tableview or grid view??
Any Help is Appreciated.
Finally I figure it to display All contain same as on other device by using Include tag in list view layout.
<HorizontalScrollView
android:id="#+id/horizontalScrollView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<include android:id="#+id/train2" layout="#layout/train2" />
</HorizontalScrollView>
In train I have this
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal">
<include android:id="#+id/boogi1" layout="#layout/boogi" />
<include android:id="#+id/boogi2" layout="#layout/boogi" />
<include android:id="#+id/engine" layout="#layout/engine" />
And to access each Image-view and textview i used
ImageView v1 = ((ImageView)vi.findViewById(R.id.train).findViewById(R.id.boogi1).findViewById(R.id.imageView1));
Thank you for support.
Just one question is it possible to change view for every row depending on position of row..
I think you need to try Custom Listview,,,
try this http://www.androidhive.info/2012/02/android-custom-listview-with-image-and-text/.

Return Multiple TextView Values from ListView

I have a ListView with each column consisting of three TextViews (for formatting reasons).
The problem I have is when the onItemClick method is called I need to return the value for all three TextViews, which I cannot achieve using:
((TextView)view.).getText().toString();
Try assigning id's to the TextViews and then use findViewById to locate them in the view for the row item that was clicked. For example:
public void onItemClick(AdapterView<?> parent, View child, int position, long id) {
TextView titleTextView = (TextView)child.findViewById(R.id.textview_title);
TextView subtitleTextView = (TextView)child.findViewById(R.id.textview_subtitle);
TextView dateTextView = (TextView)child.findViewById(R.id.textview_date);
// Do the rest of your processing here
}
Access each TextView in the ListView like this:
listView.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View viewItem, int position, long arg3) throws NullPointerException{
TextView one = (TextView)parent.getChildAt(position-listView.getFirstVisiblePosition()).findViewById(R.id.tvone);
String tvone = one.getText().toString();
TextView two = (TextView)parent.getChildAt(position-listView.getFirstVisiblePosition()).findViewById(R.id.tvtwo);
String tvtwo = two.getText().toString();
TextView three = (TextView)parent.getChildAt(position-listView.getFirstVisiblePosition()).findViewById(R.id.tvthree);
String tvthree = three.getText().toString();
}
}
In the end, I found this worked perfectly:
String item = ((TextView)view.findViewById(R.id.TYPE_CELL)).getText().toString();

Horizontal scrolling grid view

I know it is not possible in Android to scroll grid view horizontally. But what I am doing is adding image buttons dynamically inside horizontal scroll view like this:
public class HorizontalScroller extends Activity {
static int l=0;
private Rect mTempRect = new Rect();
static int r1=0;
static int t=0;
static int b=0;
static int x=0;
static int y=0;
//Button[] b1 = new Button[100];
ImageButton btn[][] = new ImageButton[10][10];
//ImageButton b1 = new ImageButton(this);
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LinearLayout rl = (LinearLayout)findViewById(R.id.widget92);
LinearLayout.LayoutParams params1 = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
for(int i=0;i<4;i++)
{
for(int j=0;j<10;j++)
{System.out.println("helo");
/* l=l+100;
r1=r1+100;
t=t+100;
b=b+100;*/
//button();
//ImageButton btn=new ImageButton(this);
/* Rect r = mTempRect;
r.left=10;
r.top=10;
r.right=10;
r.bottom=10;
btn[i][j].getDrawingRect(r);*/
//btn[i][j].setId(j);
Rect r = mTempRect;
r.set(0,0,0,0);
Rect r2 = mTempRect;
r2.set(0,20,0,20);
btn[i][j]=new ImageButton(this);
btn[i][j]. setBackgroundResource(R.drawable.icon);
btn[i][j].setMinimumWidth(20);
btn[i][j].setMinimumHeight(20);
params1.setMargins(5, 5, 5,5);
rl.addView(btn[i][j],params1);
System.out.println("1="+btn[i][j].getTop());
System.out.println("2="+btn[i][j].getLeft());
System.out.println("3="+btn[i][j].getRight());
System.out.println("4="+btn[i][j].getBottom());
}
}
}
}
but I am getting all image buttons in a single line. How can I implement them in a grid like structure?
Implementing a horizontally scrolling GridView involves copying a few of the Android source code classes into your codebase (AdapterView, AbsListView, GridView, ScrollBarDrawable) and adding in code to handle the horizontal code. This is mainly copying some of the code and changing top to left, bottom to right, etc. The main reason for having to copy instead of extending is the final nature of those classes.
I implemented a horizontally scrolling GridView a while ago and finally got around to pushing to github:
https://github.com/jess-anders/two-way-gridview
You can
use a TableLayout inside a HorizontalScrollView, or
stay with your approach with an horizontal LinearLayout but adding vertical LinearLayouts instead of directly the images. E.g., adding three to four images per vertical LinearLayout in portrait, and redrawing to add only two in landscape.
I would try the TableLayout approach first.
PS1: for next time, try to remove all the non-relevant code (the less code is there, the easier is to understand what you did).
PS2: Remember that System.out is usually redirected to /dev/null and thus lost, so I strongly suggest you to use Log.d instead.
Complete example
Adapt this to the onCreate() method or wherever you need it:
public void horizontalScrollGalleryLayout () {
HorizontalScrollView sv = new HorizontalScrollView(this);
LinearLayout llh = new LinearLayout(this);
llh.setOrientation(LinearLayout.HORIZONTAL);
LinearLayout.LayoutParams layoutParamsTV = new LinearLayout.LayoutParams(40, 40);
LinearLayout.LayoutParams layoutParamsLL = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
for (int i=0; i<20; i++) {
LinearLayout llv = new LinearLayout(this);
llv.setOrientation(LinearLayout.VERTICAL);
TestView testView1 = new TestView(this, Color.rgb(i*12, 0, 0));
TestView testView2 = new TestView(this, true, Color.rgb(i*12, i*12, 0));
TestView testView3 = new TestView(this, true, Color.rgb(0, i*12, 0));
llv.addView(testView1, layoutParamsTV);
llv.addView(testView2, layoutParamsTV);
llv.addView(testView3, layoutParamsTV);
llh.addView(llv, layoutParamsLL);
}
sv.addView(llh, layoutParamsLL);
setContentView(sv);
}
I'm using a very simple View as an example:
public class TestView extends View {
Context context;
int color;
public TestView(Context context, int color) {
super(context);
this.context = context;
this.color = color;
}
#Override
public void onDraw (Canvas canvas) {
super.onDraw(canvas);
this.setBackgroundColor(Color.LTGRAY);
Paint paint = new Paint (Paint.ANTI_ALIAS_FLAG);
paint.setColor(color);
canvas.drawCircle(20, 20, 20, paint);
}
}
There is a very easy trick.
Rotate the grid view by 270 degree and set number of columns as 2.
Rotate each item to 90 degree (so that the items are displayed as original orientation).
This might be useful for some!!
I have done this way:
activity_main.xml:
<HorizontalScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<GridView
android:id="#+id/gridView"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</GridView>
</LinearLayout>
</HorizontalScrollView>
MainActivity.java:
GridView gridView = (GridView) findViewById(R.id.gridView);
gridView.setNumColumns(arrayList.size());
GridViewAdapter gridViewAdapter = new GridViewAdapter(mContext, arrayList);
gridView.setAdapter(gridViewAdapter);
// Set dynamic width of Gridview
setDynamicWidth(gridView);
Add below method:
private void setDynamicWidth(GridView gridView) {
ListAdapter gridViewAdapter = gridView.getAdapter();
if (gridViewAdapter == null) {
return;
}
int totalWidth;
int items = gridViewAdapter.getCount();
View listItem = gridViewAdapter.getView(0, null, gridView);
listItem.measure(0, 0);
totalWidth = listItem.getMeasuredWidth();
totalWidth = totalWidth*items;
ViewGroup.LayoutParams params = gridView.getLayoutParams();
params.width = totalWidth;
gridView.setLayoutParams(params);
}
Hope this will help you.
I have already posted this answer here, but both questions are
identical...
There is a nice solution in Android from now on : HorizontalGridView.
1. Gradle dependency
dependencies {
compile 'com.android.support:leanback-v17:23.1.0'
}
2. Add it in your layout
your_activity.xml
<!-- your stuff before... -->
<android.support.v17.leanback.widget.HorizontalGridView
android:layout_width="wrap_content"
android:layout_height="80dp"
android:id="#+id/gridView"
/>
<!-- your stuff after... -->
3. Layout grid element
Create a layout for your grid element ( grid_element.xml ). I have created a simple one with only one button in it.
<?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">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="#+id/button" />
</LinearLayout>
4. Create an adapter
Highly inspired by this link : https://gist.github.com/gabrielemariotti/4c189fb1124df4556058
public class GridElementAdapter extends RecyclerView.Adapter<GridElementAdapter.SimpleViewHolder>{
private Context context;
private List<String> elements;
public GridElementAdapter(Context context){
this.context = context;
this.elements = new ArrayList<String>();
// Fill dummy list
for(int i = 0; i < 40 ; i++){
this.elements.add(i, "Position : " + i);
}
}
public static class SimpleViewHolder extends RecyclerView.ViewHolder {
public final Button button;
public SimpleViewHolder(View view) {
super(view);
button = (Button) view.findViewById(R.id.button);
}
}
#Override
public SimpleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
final View view = LayoutInflater.from(this.context).inflate(R.layout.grid_element, parent, false);
return new SimpleViewHolder(view);
}
#Override
public void onBindViewHolder(SimpleViewHolder holder, final int position) {
holder.button.setText(elements.get(position));
holder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(context, "Position =" + position, Toast.LENGTH_SHORT).show();
}
});
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemCount() {
return this.elements.size();
}
}
5. Initialize it in your activity :
private HorizontalGridView horizontalGridView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_activity);
horizontalGridView = (HorizontalGridView) findViewById(R.id.gridView);
GridElementAdapter adapter = new GridElementAdapter(this);
horizontalGridView.setAdapter(adapter);
}
Use recyclerview with setting its gridlayout as layout manager and set it to horizontal scroll
your recycle view.setLayoutManager(new GridLayoutManager(getActivity(),2, LinearLayoutManager.HORIZONTAL, false))
here 2 is the column span for grid

Categories

Resources