How to use a custom layout as RadioButton label - android

I made a custom layout that I want to implement for a RadioButton.
The code for the android class is here :
public class MyRadioButton extends LinearLayout implements View.OnClickListener{
private ImageView iv;
private TextView tv;
private RadioButton rb;
private View view;
public MyRadioButton(Context context) {
super(context);
view = View.inflate(context, R.layout.my_radio_button, this);
setOrientation(HORIZONTAL);
rb = (RadioButton) view.findViewById(R.id.radioButton1);
tv = (TextView) view.findViewById(R.id.textView1);
iv = (ImageView) view.findViewById(R.id.imageView1);
view.setOnClickListener(this);
rb.setOnCheckedChangeListener(null);
}
public void setImageBitmap(Bitmap bitmap) {
iv.setImageBitmap(bitmap);
}
public View getView() {
return view;
}
#Override
public void onClick(View v) {
boolean nextState = !rb.isChecked();
LinearLayout lGroup = (LinearLayout)view.getParent();
if(lGroup != null){
int child = lGroup.getChildCount();
for(int i=0; i<child; i++){
//uncheck all
((RadioButton)lGroup.getChildAt(i).findViewById(R.id.radioButton1)).setChecked(false);
}
}
rb.setChecked(nextState);
}
public void setImage(Bitmap b){
iv.setImageBitmap(b);
}
public void setText(String text){
tv.setText(text);
}
public void setChecked(boolean isChecked){
rb.setChecked(isChecked);
}
}
And the code for layout is here
<?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="wrap_content"
android:gravity="center_vertical"
android:orientation="horizontal" >
<RadioButton
android:id="#+id/radioButton1"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="top"
android:text="" />
<LinearLayout
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium" />
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/wow_visa_prepaid" />
</LinearLayout>
</LinearLayout>
At this moment, I can't figure out how to change the inheritance from LinearLayout to RadioButton and to keep the same layout.
This should like but with rounded corners

There are two ways to do the job:
1. When we hear about a custom view, it drives us to override onDraw method then drawing what we want into the view's Canvas.
2. In this case, there is a simpler approach, using drawableLeft. Here I've extended AppCompatRadioButton and set the considered layout as the drawableLeft.
MyRadioButton.java
package com.aminography.radiobutton;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.MultiTransformation;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.Target;
import jp.wasabeef.glide.transformations.MaskTransformation;
// TODO: If you are using androidx
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatRadioButton;
// TODO: If you are using appcompat
//import android.support.annotation.Nullable;
//import android.support.v7.widget.AppCompatRadioButton;
public class MyRadioButton extends AppCompatRadioButton {
private View view;
private TextView textView;
private ImageView imageView;
public MyRadioButton(Context context) {
super(context);
init(context);
}
public MyRadioButton(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public MyRadioButton(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context);
}
private RequestListener<Bitmap> requestListener = new RequestListener<Bitmap>() {
#Override
public boolean onLoadFailed(#Nullable GlideException e, Object model, Target<Bitmap> target, boolean isFirstResource) {
return false;
}
#Override
public boolean onResourceReady(Bitmap resource, Object model, Target<Bitmap> target, DataSource dataSource, boolean isFirstResource) {
imageView.setImageBitmap(resource);
redrawLayout();
return false;
}
};
public void setImageResource(int resId) {
Glide.with(getContext())
.asBitmap()
.load(resId)
.apply(RequestOptions.bitmapTransform(
new MultiTransformation<>(
new CenterCrop(),
new RoundedCornersTransformation(dp2px(getContext(), 24), 0, RoundedCornersTransformation.CornerType.ALL))
)
)
.listener(requestListener)
.submit();
}
public void setImageBitmap(Bitmap bitmap) {
Glide.with(getContext())
.asBitmap()
.load(bitmap)
.apply(RequestOptions.bitmapTransform(
new MultiTransformation<>(
new CenterCrop(),
new RoundedCornersTransformation(dp2px(getContext(), 24), 0, RoundedCornersTransformation.CornerType.ALL))
)
)
.listener(requestListener)
.submit();
}
// setText is a final method in ancestor, so we must take another name.
public void setTextWith(int resId) {
textView.setText(resId);
redrawLayout();
}
public void setTextWith(CharSequence text) {
textView.setText(text);
redrawLayout();
}
private void init(Context context) {
view = LayoutInflater.from(context).inflate(R.layout.my_radio_button_content, null);
textView = view.findViewById(R.id.textView);
imageView = view.findViewById(R.id.imageView);
redrawLayout();
}
private void redrawLayout() {
view.setDrawingCacheEnabled(true);
view.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
view.buildDrawingCache(true);
Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache());
setCompoundDrawablesWithIntrinsicBounds(new BitmapDrawable(getResources(), bitmap), null, null, null);
view.setDrawingCacheEnabled(false);
}
private int dp2px(Context context, int dp) {
return (int) (dp * context.getResources().getDisplayMetrics().density);
}
}
my_radio_button_content.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:orientation="vertical">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium" />
<ImageView
android:id="#+id/imageView"
android:layout_width="96dp"
android:layout_height="64dp"
android:src="#drawable/img_visa" />
</LinearLayout>
Visual Result:
Note:
1. If you're using appcompat in the project, do comment the androidx import at the top of class and uncomment appcompat one.
2. You can change the position of the custom layout simply by changing android:paddingLeft for your RadioButton:
<com.aminography.radiobutton.MyRadioButton
android:id="#+id/radioButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="8dp" />
Edited:
I've rewritten the code to address the requirement of rounded corners image using Glide and Glide-Transformations.
build.gradle
dependencies {
implementation 'com.github.bumptech.glide:glide:4.9.0'
implementation 'jp.wasabeef:glide-transformations:3.3.0'
}

I have tried the following code and it works fine with no error:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<com.example.myapplication.MyRadioButton
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
After changing the following code from:
public MyRadioButton(Context context) {
to the following code:
public MyRadioButton(Context context, AttributeSet attributes) {
Is this the solution you need?

1. When you are creating class, that extends LinearLayout or
FrameLayout, .xml layout file (my_radio_button_content.xml),
must start with "merge" instead "LinearLayout", otherwise it
will be LinearLayot(.xml) in LinearLayout(your class).
<merge>
<RadioButton
android:id="#+id/radioButton1"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="top"
android:text="" />
<LinearLayout
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium" />
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/wow_visa_prepaid" />
</LinearLayout>
</merge>
2. It's easy to create: final ArrayList<MyRadioButton>, and pass it
to all children, if you want that brothers will change each
others.
public MyRadioButton(Context context) {
super(context);
inflate(context, R.layout.my_radio_button, this);
}
public void SetMyViewClickable(final ArrayList<String> brothers) {
setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
for (View brother:brothers) {
((RadioButton)brother.findViewById(R.id.radioButton1)).setChecked(false);
}
}
});
}

There are many ways to do this, for example, you can use the following libraries
https://github.com/AagitoEx/ImageRadioButton
https://github.com/ceryle/RadioRealButton

Related

GridView item looks not as expected - Android

I try to use a GridView object in a specific fragment in my app.
I created a layout file for the grid item and in the layout editor, the preview image looks good, as expected.
The problem arises when I run the app in my emulator. The whole item layout gets shrinked and the image I put in the middle suddenly jumps to the top of the layout.
Screenshot of the layout editor:
https://i.gyazo.com/8ed96ed19719a578388cc48aba6829f8.png
Screenshot of the emulator:
https://i.gyazo.com/cca0a32b3d102025df5d5369dc7c0efc.png
Here is the xml code for the fragment:
<?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">
<GridView
android:id="#+id/documents_grid"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="10dp"
android:columnWidth="#dimen/document_grid_item_width"
android:gravity="center"
android:horizontalSpacing="0dp"
android:verticalSpacing="0dp"
android:numColumns="auto_fit"
android:stretchMode="spacingWidthUniform" />
<RelativeLayout
android:id="#+id/empty_view_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/empty_view_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:src="#drawable/recent_empty_view" />
<ImageView
android:id="#+id/empty_view_arrow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignEnd="#+id/empty_view_image"
android:layout_below="#+id/empty_view_image"
android:layout_marginEnd="7dp"
android:scaleX="0.75"
android:scaleY="0.75"
android:src="#drawable/empty_view_arrow" />
</RelativeLayout>
</RelativeLayout>
Here is the item layout xml code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="#dimen/document_grid_item_width"
android:layout_height="#dimen/document_grid_item_height"
android:gravity="center"
android:orientation="vertical"
android:weightSum="1">
<FrameLayout
android:id="#+id/draft_frame"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.9"
android:background="#drawable/document_grid_item_bg"
android:focusable="true"
android:foreground="?android:selectableItemBackground">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/draft_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:src="#drawable/draft_icon" />
<ImageView
android:id="#+id/draft_more_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentTop="true"
android:layout_marginTop="5dp"
app:srcCompat="#drawable/ic_more" />
</RelativeLayout>
</FrameLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_margin="5dp"
android:layout_weight="0.1">
<TextView
android:id="#+id/draft_date_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="20 May 17"
android:textSize="11sp" />
</RelativeLayout>
</LinearLayout>
Here is the adapter code:
package com.silverfix.dgdeditor.adapters;
import android.app.Activity;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.silverfix.dgdeditor.R;
import com.silverfix.dgdeditor.utils.DocumentPack;
import com.silverfix.dgdeditor.utils.views.ViewClickListener;
import com.silverfix.dgdeditor.utils.views.ViewLongClickListener;
import java.util.List;
/**
* Created by David on 14/05/2017.
*/
public class DraftsGridAdapter extends BaseAdapter {
// Listeners
private ViewClickListener clickListener;
private ViewLongClickListener longClickListener;
private Activity context;
private List<DocumentPack> dataSet;
private int clickedItemPos = -1;
public DraftsGridAdapter(Activity context, List<DocumentPack> dataSet) {
this.context = context;
this.dataSet = dataSet;
}
public void setClickedItemPosition(int clickedItemPos) {
this.clickedItemPos = clickedItemPos;
}
public int getClickedItemPosition() {
return clickedItemPos;
}
public void setClickListener(ViewClickListener clickListener) {
this.clickListener = clickListener;
}
public void setLongClickListener(ViewLongClickListener longClickListener) {
this.longClickListener = longClickListener;
}
#Override
public int getCount() {
return dataSet.size();
}
#Override
public Object getItem(int position) {
return dataSet.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final DocumentPack pack = dataSet.get(position);
if (convertView == null) {
final LayoutInflater inflater = LayoutInflater.from(context);
convertView = inflater.inflate(R.layout.draft_grid_item, null);
DraftViewHolder viewHolder = new DraftViewHolder(context, convertView);
convertView.setTag(viewHolder);
}
// Instance of a view holder from the tag of the convertView
DraftViewHolder viewHolder = (DraftViewHolder) convertView.getTag();
// Set the adapter position to the current view holder
viewHolder.setAdapterPosition(position);
// Bind the click listeners to the root view of the view holder
// viewHolder.bindClick(clickListener);
// viewHolder.bindLongClick(longClickListener);
// Bind the data to the view holder
viewHolder.bindData(pack);
return convertView;
}
private class DraftViewHolder implements View.OnCreateContextMenuListener {
private View.OnClickListener clickListener;
private View.OnLongClickListener onLongClickListener;
private View rootView;
private ImageView moreButton;
private TextView date;
private int position;
public DraftViewHolder(final Activity context, final View rootView) {
this.rootView = rootView;
date = (TextView) rootView.findViewById(R.id.draft_date_tv);
moreButton = (ImageView) rootView.findViewById(R.id.draft_more_button);
context.registerForContextMenu(rootView);
rootView.setOnCreateContextMenuListener(this);
moreButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
context.openContextMenu(rootView);
setClickedItemPosition(position);
}
});
}
void setAdapterPosition(int position) {
this.position = position;
}
void bindClick(final ViewClickListener clickListener) {
this.clickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
clickListener.onClick(position);
}
};
rootView.setOnClickListener(this.clickListener);
}
void bindLongClick(final ViewLongClickListener longClickListener) {
this.onLongClickListener = new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
longClickListener.onLongClick(position);
return false;
}
};
rootView.setOnLongClickListener(this.onLongClickListener);
}
void bindData(DocumentPack draft) {
String formatDate = draft.getFormattedDate();
date.setText(formatDate);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
}
}
}
This worked for me, You can try...
`<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:padding="5dp" >
<GridView
android:id="#+id/gridview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:columnWidth="100dp"
android:gravity="center"
android:horizontalSpacing="10dp"
android:numColumns="3"
android:stretchMode="spacingWidthUniform"
android:verticalSpacing="10dp" />
`
If this don't work you can also try to use android:stretchMode="columnWidth"

weights are not working correctly in linear layout

I'm a beginner in android development.I'm trying to make a layout,which support both landscape and portrait images.
For,example if the image is portrait then there should be white spaces around it and if the image is landscape then it would take the whole width of the imageview and both of them should maintain the aspect ratio.I'm using json to get images from the URL and using array adapter to inflate the layout in listview.
When the layout is inflated one the linear layout's weight changes automatically
and I have no idea why it's doing like that? What should be the approach to do that should, I scale the image using java or is there any other way around?
Here are the screenshots of the layout
First row of the listview
Second row pf the listview
Note:You can see that in the second screenshot, the height of the first linear layout is bigger than the linear layout in the first screenshot(where user's profile picture is shown)
timelinerowlayout.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ccc"
android:padding="10dp">
<!-- A CardView that contains a TextView -->
<android.support.v7.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/card_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
card_view:cardCornerRadius="5dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="3">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.35"
android:background="#drawable/border">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp">
<com.makeramen.roundedimageview.RoundedImageView xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/userProfilePicture"
android:layout_width="40dp"
android:layout_height="match_parent"
android:src="#drawable/ppplaceholder"
app:riv_border_color="#333333"
app:riv_border_width="2dip"
app:riv_corner_radius="5dip"
app:riv_mutate_background="true"
app:riv_oval="true"
app:riv_tile_mode="repeat" />
<TextView
android:id="#+id/username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="5dp"
android:layout_toEndOf="#+id/userProfilePicture"
android:layout_toRightOf="#+id/userProfilePicture"
android:text="Small Text"
android:textAppearance="?android:attr/textAppearanceSmall" />
</RelativeLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1.5">
<ImageView
android:id="#+id/userpostimage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:scaleType="fitCenter"
android:src="#drawable/bc" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1.16">
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/swipe_refresh_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.gitesh.timeline.MainActivity">
<ListView
android:id="#+id/listview"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
</android.support.v4.widget.SwipeRefreshLayout>
MainActivity.java
package com.example.gitesh.timeline;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.widget.AbsListView;
import android.widget.ListView;
import android.widget.Toast;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.TextHttpResponseHandler;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import Classes.PostAdapter;
import Classes.posts;
import cz.msebera.android.httpclient.Header;
public class MainActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener {
ListView datalist;
PostAdapter PostAdapter;
private SwipeRefreshLayout swipeRefreshLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
datalist = (ListView) findViewById(R.id.listview);
datalist.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if (datalist.getChildAt(0) != null) {
swipeRefreshLayout.setEnabled(datalist.getFirstVisiblePosition() == 0 && datalist.getChildAt(0).getTop() == 0);
}
}
});
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
Typeface cFont = Typeface.createFromAsset(getAssets(), "SAMARN__.TTF");
Typeface fontAwesome = Typeface.createFromAsset(getAssets(), "fontawesome-webfont.ttf");
PostAdapter = new PostAdapter(this, R.layout.timelinerowlayout, cFont);
datalist.setAdapter(PostAdapter);
swipeRefreshLayout.setOnRefreshListener(this);
/**
* Showing Swipe Refresh animation on activity create
* As animation won't start on onCreate, post runnable is used
*/
swipeRefreshLayout.post(new Runnable() {
#Override
public void run() {
swipeRefreshLayout.setRefreshing(true);
bindData();
}
}
);
}
/**
* This method is called when swipe refresh is pulled down
*/
#Override
public void onRefresh() {
bindData();
}
public void bindData() {
try {
AsyncHttpClient client = new AsyncHttpClient(true, 80, 443);
client.get("http://indianroute.roms4all.com/fetch_post.php", new TextHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, String res) {
decodeJson(res);
}
#Override
public void onFailure(int statusCode, Header[] headers, String res, Throwable t) {
// called when response HTTP status is "4XX" (eg. 401, 403, 404)
Toast.makeText(MainActivity.this, "" + res, Toast.LENGTH_SHORT).show();
}
}
);
} catch (Exception e) {
Toast.makeText(MainActivity.this, "" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
private void decodeJson(String result) {
try {
swipeRefreshLayout.setRefreshing(true);
JSONArray jArr = new JSONArray(result);
String username, story, picture, check_in, userprofilePicture;
for (int count = 0; count < jArr.length(); count++) {
JSONObject obj = jArr.getJSONObject(count);
username = obj.getString("username");
story = obj.getString("story");
picture = obj.getString("picture");
check_in = obj.getString("check_in");
userprofilePicture = obj.getString("userprofilePicture");
posts posts = new posts(username, story, picture, check_in, userprofilePicture);
swipeRefreshLayout.setRefreshing(false);
PostAdapter.add(posts);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
PostAdapter.java
package Classes;
import android.content.Context;
import android.graphics.Typeface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.gitesh.timeline.R;
import com.makeramen.roundedimageview.RoundedImageView;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Gitesh on 14-06-2016.
*/
public class PostAdapter extends ArrayAdapter {
List list = new ArrayList();
Typeface samarn;
public PostAdapter(Context context, int resource, Typeface cFont) {
super(context, resource);
samarn = cFont;
}
#Override
public void add(Object object) {
super.add(object);
list.add(object);
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row;
row = convertView;
PostHolder postHolder;
if (row == null) {
LayoutInflater layoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.timelinerowlayout, parent, false);
postHolder = new PostHolder();
postHolder.username = (TextView) row.findViewById(R.id.username);
postHolder.userPostImage = (ImageView) row.findViewById(R.id.userpostimage);
postHolder.userprofilePicture = (RoundedImageView) row.findViewById(R.id.userProfilePicture);
row.setTag(postHolder);
} else {
postHolder = (PostHolder) row.getTag();
}
posts posts = (posts) this.getItem(position);
postHolder.username.setTypeface(samarn);
postHolder.username.setText(posts.getUsername());
Picasso.with(getContext()).load(posts.getUserProfilePicture()).placeholder(R.drawable.ppplaceholder).priority(Picasso.Priority.HIGH).into(postHolder.userprofilePicture);
Picasso.with(getContext()).load(posts.getPictue()).placeholder(R.drawable.postplaceholder).into(postHolder.userPostImage);
return row;
}
static class PostHolder {
TextView username;
ImageView userPostImage;
com.makeramen.roundedimageview.RoundedImageView userprofilePicture;
}
}
If you are using horizontal linear layout(android:orientation="horizontal") then make width as 0dpand if it is vertical linear layout give height as 0dp
.Then give weights to child views.
You have defined weight_sum = 3 and the inner views of that layout have weight 0.35, 1.5 and 1.16 accordingly.
0.35 + 1.5 + 1.16 = 3.01
So the sum of the weight you have defined to your inner views does not exactly equal to 3
Try replacing your layout with this, i've changed layout weights
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ccc"
android:padding="10dp">
<!-- A CardView that contains a TextView -->
<android.support.v7.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/card_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
card_view:cardCornerRadius="5dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0"
android:background="#drawable/border">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp">
<com.makeramen.roundedimageview.RoundedImageView xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/userProfilePicture"
android:layout_width="40dp"
android:layout_height="wrap_content"
android:src="#drawable/ppplaceholder"
app:riv_border_color="#333333"
app:riv_border_width="2dip"
app:riv_corner_radius="5dip"
app:riv_mutate_background="true"
app:riv_oval="true"
app:riv_tile_mode="repeat" />
<TextView
android:id="#+id/username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="5dp"
android:layout_toEndOf="#+id/userProfilePicture"
android:layout_toRightOf="#+id/userProfilePicture"
android:text="Small Text"
android:textAppearance="?android:attr/textAppearanceSmall" />
</RelativeLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1.3">
<ImageView
android:id="#+id/userpostimage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:scaleType="fitCenter"
android:src="#drawable/bc" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
</LinearLayout>

Custom component Android LinearLayout not visible

Custom LinearLayout component view not displaying content
Hi i have created a custom component view that extends LinearLayout and when i use this view on my xml, it doesnt become visible on the screen.
Here is the main view that is using this custom component
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/contentLinearLayout"
android:layout_width="#dimen/width"
android:layout_height="wrap_content"
android:orientation="vertical">
<ImageView
android:id="#+id/image"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#ABB0B6" />
<com.jon.ui.EnableView
android:id="#+id/enableContainter"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
Here is the EnableView custom component code:
package com.jon.ui;
/**
*/
public class EnableView extends LinearLayout {
private static View enableView;
private static Button btnContactlessInfoAction;
private static LinearLayout btnMakeContactlessAction;
private static View makeContactlessView;
private static View.OnClickListener enableContaclessBtnClick = new View.OnClickListener() {
#Override
public void onClick(View v) {
}
};
private static View.OnClickListener contactlessHelpBtnClick = new View.OnClickListener() {
#Override
public void onClick(View v) {
}
};
private static ViewGroup viewContainer;
private final Context mContext;
public EnableContactlessView(Context context) {
super(context);
mContext = context;
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.custom_component, this);
setOrientation(LinearLayout.VERTICAL);
}
public EnableContactlessView(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.custom_component, this);
setOrientation(LinearLayout.VERTICAL);
}
#Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
}
public void initiate() {
btnMakeContactlessAction = (LinearLayout) this.findViewById(R.id.btn);
btnContactlessInfoAction = (Button) this.findViewById(R.id.info_btn);
btnContactlessInfoAction.setOnClickListener(contactlessHelpBtnClick);
}
#Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
}
}
Below is the
View's layout xml i use to inflate from EnableView class called custom_component.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/top_margin"
android:gravity="center_horizontal"
android:orientation="horizontal">
<LinearLayout
android:id="#+id/btn"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginRight="9dp"
android:layout_weight="3"
android:background="#color/button_colour"
android:gravity="center"
android:paddingBottom="9dp"
android:paddingTop="9dp">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="15dp"
android:src="#drawable/icon_symbol" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="activate and enable"
android:textColor="#android:color/white" />
</LinearLayout>
<Button
android:id="#+id/info_btn"
android:layout_width="25dp"
android:layout_height="25dp"
android:layout_gravity="center_vertical|end"
android:background="#drawable/icon" />
</LinearLayout>
Do not override onLayout if you're leaving it empty, remove that function. onLayout is used to measure the parent and its children, if you leave it empty nothing is getting measured.

Android Spinner is unable to scroll

I use Spinner in my app, with keyboard opened.
This Spinner has 9 items (from 1 to 9).
However if keyboard is opened, spinner cannot be scrolled!
Thanks to it, some of items are out of screen, and I cannot select them.
Dialog Layout here:
<?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">
<com.material.widget.FloatingEditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/fet_productName"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="#dimen/floating_edittext_margin"
android:layout_marginRight="#dimen/floating_edittext_margin"
android:hint="#string/product_name"
android:inputType="text" />
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/fet_productName"
android:layout_alignLeft="#+id/fet_productName"
android:layout_alignStart="#+id/fet_productName"
android:layout_alignRight="#+id/fet_productName"
android:layout_alignEnd="#+id/fet_productName"
android:layout_marginTop="#dimen/space_20dp"
android:id="#+id/linearLayout2">
<com.material.widget.FloatingEditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/fet_productUnit"
android:layout_weight="1"
android:hint="#string/product_unit"
android:inputType="text"
android:layout_marginRight="#dimen/space_6dp" />
<Spinner
android:layout_width="80dp"
android:layout_height="wrap_content"
android:id="#+id/sP_dialog_productNumber"
android:entries="#array/spinner_cart_item_number"
android:layout_marginLeft="#dimen/space_6dp" />
</LinearLayout>
</RelativeLayout>
Java code here:
public class CartFragment extends Fragment {
private Spinner spNum;
private MaterialDialog dialog;
private static String[] msITEMS;
private ArrayList<CartItemData> itemDatas;
private ArrayAdapter<String> strAdapter;
public CartFragment(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_placeholder_cart, container, false);
msITEMS = rootView.getContext().getResources().getStringArray(R.array.spinner_dialog_item_number);
strAdapter = new ArrayAdapter<String>(rootView.getContext(), R.layout.support_simple_spinner_dropdown_item, msITEMS);
strAdapter.setDropDownViewResource(R.layout.support_simple_spinner_dropdown_item);
final FloatingActionButton fabAdd = (FloatingActionButton)rootView.findViewById(R.id.fabAdd);
fabAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog = new MaterialDialog.Builder(getActivity())
.title(R.string.product_title)
.customView(R.layout.dialog_add_cartitem, false)
.positiveText(R.string.dialog_positive_add_cartitem)
.negativeText(R.string.dialog_negative_add_cartitem)
.show();
View view = dialog.getCustomView();
dialog.getActionButton(DialogAction.POSITIVE).setEnabled(false);
spNum = (Spinner)view.findViewById(R.id.sP_dialog_productNumber);
fetName = (FloatingEditText)view.findViewById(R.id.fet_productName);
fetUnit = (FloatingEditText)view.findViewById(R.id.fet_productUnit);
spNum.setAdapter(strAdapter);
dialog.getActionButton(DialogAction.POSITIVE).setOnClickListener(onPositiveClick());
}
});
return rootView;
}
public void onActivityCreated (Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
}
Create a custom scroll:
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import org.holoeverywhere.widget.ListPopupWindow;
import org.holoeverywhere.widget.ListView;
import org.holoeverywhere.widget.Spinner;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.View;
public class CustomSpinner extends Spinner
{
public CustomSpinner(Context context)
{
super(context);
}
public CustomSpinner(Context context, AttributeSet attrs)
{
super(context, attrs);
}
public CustomSpinner(Context context, AttributeSet attrs, int defStyle)
{
super(context, attrs, defStyle);
}
public CustomSpinner(Context context, AttributeSet attrs, int defStyle, int mode)
{
super(context, attrs, defStyle, mode);
}
public CustomSpinner(Context context, int mode)
{
super(context, mode);
}
#Override
public boolean performClick()
{
boolean bClicked = super.performClick();
try
{
Field mPopupField = Spinner.class.getDeclaredField("mPopup");
mPopupField.setAccessible(true);
ListPopupWindow pop = (ListPopupWindow) mPopupField.get(this);
ListView listview = pop.getListView();
Field mScrollCacheField = View.class.getDeclaredField("mScrollCache");
mScrollCacheField.setAccessible(true);
Object mScrollCache = mScrollCacheField.get(listview);
Field scrollBarField = mScrollCache.getClass().getDeclaredField("scrollBar");
scrollBarField.setAccessible(true);
Object scrollBar = scrollBarField.get(mScrollCache);
Method method = scrollBar.getClass().getDeclaredMethod("setVerticalThumbDrawable", Drawable.class);
method.setAccessible(true);
method.invoke(scrollBar, getResources().getDrawable(R.drawable.scrollbar_style));
if(VERSION.SDK_INT >= VERSION_CODES.HONEYCOMB)
{
Field mVerticalScrollbarPositionField = View.class.getDeclaredField("mVerticalScrollbarPosition");
mVerticalScrollbarPositionField.setAccessible(true);
mVerticalScrollbarPositionField.set(listview, SCROLLBAR_POSITION_LEFT);
}
}
catch(Exception e)
{
e.printStackTrace();
}
return bClicked;
}
}
As shown on this other post by End.Fouad
I found one solution but it makes UX worse.
When the activity is appeared I focus a view which isn't a input view.
<?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:focusable="true"
android:focusableInTouchMode="true" >
<com.material.widget.FloatingEditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/fet_productName"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="#dimen/floating_edittext_margin"
android:layout_marginRight="#dimen/floating_edittext_margin"
android:hint="#string/product_name"
android:inputType="text" />
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/fet_productName"
android:layout_alignLeft="#+id/fet_productName"
android:layout_alignStart="#+id/fet_productName"
android:layout_alignRight="#+id/fet_productName"
android:layout_alignEnd="#+id/fet_productName"
android:layout_marginTop="#dimen/space_20dp"
android:id="#+id/linearLayout2">
<com.material.widget.FloatingEditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/fet_productUnit"
android:layout_weight="1"
android:hint="#string/product_unit"
android:inputType="text"
android:layout_marginRight="#dimen/space_6dp" />
<Spinner
android:layout_width="80dp"
android:layout_height="wrap_content"
android:id="#+id/sP_dialog_productNumber"
android:entries="#array/spinner_cart_item_number"
android:layout_marginLeft="#dimen/space_6dp" >
</Spinner>
</LinearLayout>
<requestFocus/>
</RelativeLayout>
android:focusable="true"
android:focusableInTouchMode="true"
<requestFocus/>
Delete the following line in your 'Activity':
getWindow().setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
or if you are using any such flags...

Using expandableheadergridview working fine on Android L but crashes on Devices<=4.4

I am using the expandableheadergridview in my app for adding gridview inside scrollview. It works completely fine on Android L but the app crashes on Devices <= 4.4.4. Cant figure out why is this happening.
My Layout file
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res/com.hj.app"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<com.hj.app.widgets.CustomScrollView
android:id="#+id/scrollview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<include layout="#layout/feed_view_header_layout" />
<LinearLayout
android:id="#+id/hj_photo_desc_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="#dimen/hj_item_height"
android:background="#android:color/white"
android:orientation="vertical" >
<TextView
android:id="#+id/hj_feed_title_text"
style="#style/HJAppTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:gravity="center_vertical"
android:minHeight="#dimen/hj_item_height"
android:text="This is a Photo"
android:textColor="#color/hj_grey_color"
android:textSize="#dimen/hj_font_large"
android:textStyle="bold" />
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#color/hj_feed_bg"
android:clipToPadding="false" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="#dimen/hj_margin_small"
android:paddingLeft="#dimen/hj_margin_medium"
android:paddingRight="#dimen/hj_margin_medium"
android:paddingTop="#dimen/hj_margin_small" >
<com.hj.app.widgets.CircularImageView
android:id="#+id/user_profile_image"
android:layout_width="#dimen/hj_source_pic_size"
android:layout_height="#dimen/hj_source_pic_size"
android:layout_centerVertical="true"
android:src="#drawable/ic_launcher"
app:border="true"
app:border_color="#android:color/white"
app:border_width="#dimen/hj_circular_image_border_width"
app:shadow="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="#dimen/hj_margin_small"
android:layout_marginStart="#dimen/hj_margin_small"
android:layout_toEndOf="#+id/user_profile_image"
android:layout_toRightOf="#+id/user_profile_image"
android:text="Umesh"
android:textColor="#color/hj_grey_color"
android:textSize="#dimen/hj_font_medium" />
</RelativeLayout>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#color/hj_feed_bg"
android:clipToPadding="false" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:lineSpacingExtra="2dp"
android:paddingBottom="#dimen/hj_margin_small"
android:paddingLeft="#dimen/hj_margin_medium"
android:paddingRight="#dimen/hj_margin_medium"
android:paddingTop="#dimen/hj_margin_small"
android:singleLine="false"
android:text="#string/dummy_desc_text"
android:textColor="#color/hj_grey_color"
android:textSize="#dimen/hj_font_small" />
<TextView
style="#style/HJAppTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hj_related_product_text"
android:textColor="#color/hj_grey_color"
android:textSize="#dimen/hj_font_medium"
android:textStyle="bold" />
<include
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="#dimen/hj_margin_medium"
android:layout_marginTop="#dimen/hj_margin_small"
layout="#layout/hj_related_items_grid_layout" />
</LinearLayout>
</LinearLayout>
</com.hj.app.widgets.CustomScrollView>
<include
android:layout_width="match_parent"
android:layout_height="#dimen/hj_item_height"
android:layout_gravity="bottom"
layout="#layout/hj_bottom_bar_layout" />
<include layout="#layout/hj_toolbar_layout" />
</FrameLayout>
ExpandableHeaderGridView file
package com.hj.app.widgets;
import android.content.Context;
import android.util.AttributeSet;
import android.view.ViewGroup;
import android.widget.GridView;
public class ExpandableHeightGridView extends GridView {
boolean expanded = false;
public ExpandableHeightGridView(Context context) {
super(context);
}
public ExpandableHeightGridView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ExpandableHeightGridView(Context context, AttributeSet attrs,
int defStyle) {
super(context, attrs, defStyle);
}
public boolean isExpanded() {
return expanded;
}
#Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (isExpanded()) {
// Calculate entire height by providing a very large height hint.
// View.MEASURED_SIZE_MASK represents the largest height possible.
int expandSpec = MeasureSpec.makeMeasureSpec(MEASURED_SIZE_MASK,
MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, expandSpec);
ViewGroup.LayoutParams params = getLayoutParams();
params.height = getMeasuredHeight();
} else {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
public void setExpanded(boolean expanded) {
this.expanded = expanded;
}
}
It crashes in ExpandableHeightGridView at line
super.onMeasure(widthMeasureSpec, expandSpec);
with the following error inside onmesure with isExpandedtrue.
Error:
java.lang.ClassCastException: android.widget.FrameLayout$LayoutParams cannot be cast to android.widget.AbsListView$LayoutParams
Can't figure out why is this happening.
Pls Help!!!!!
Edit1:
My adapter class for populating data in the grid.
package com.hj.app.adapters;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.FrameLayout.LayoutParams;
import android.widget.ImageView;
import android.widget.TextView;
import com.hj.app.R;
public class HJRelatedItemGridAdapter extends BaseAdapter {
Context mContext;
int itemHeight;
public HJRelatedItemGridAdapter(Context context) {
this.mContext = context;
}
#Override
public int getCount() {
return 10;
}
public void setItemHeight(int itemHeight) {
this.itemHeight = itemHeight;
}
#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(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(mContext).inflate(
R.layout.hj_related_items_grid_item_layout, parent, false);
GridItemHolder holder = new GridItemHolder(convertView);
convertView.setTag(holder);
}
GridItemHolder holder = (GridItemHolder) convertView.getTag();
LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT,
itemHeight);
holder.parentLayout.setLayoutParams(lp);
return convertView;
}
public class GridItemHolder {
ImageView img;
TextView titleText;
FrameLayout parentLayout;
/**
* #param itemView
*/
public GridItemHolder(View view) {
img = (ImageView) view.findViewById(R.id.hj_grid_image);
titleText = (TextView) view.findViewById(R.id.hj_grid_title_text);
parentLayout = (FrameLayout) view.findViewById(R.id.hj_grid_parent);
}
}
}
In your adapter class instead of importing
import android.widget.FrameLayout.LayoutParams;
import
import android.widget.AbsListView.LayoutParams;
because parent of item of grid view is AbsListView not FrameLayout.

Categories

Resources