Seekbar on top of clickable ImageView - android

I'm rather new to this, so apologies if it's simple. I have a GridLayout which is 2 by 4, with images that can be clicked, the image changes and a sound plays.
I would like to add a volume control on top of each image, that will control that image noises volume. How can I do this?
<GridLayout
android:id="#+id/mainGrid"
android:layout_width="0dp"
android:layout_height="0dp"
android:background="#color/colorPrimary"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent">
<ImageView
android:id="#+id/whitenoise"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="0"
android:layout_columnWeight="1"
android:layout_gravity="fill"
android:layout_row="0"
android:layout_rowWeight="1"
android:adjustViewBounds="true"
android:background="#android:color/transparent"
android:onClick="whiteNoiseTapped"
android:scaleType="fitXY"
android:text="White 1"
app:srcCompat="#drawable/whitenoise" />

Use FrameLayout for this.
<FrameLayout>
<ImageView>
android:id="#+id/whitenoise"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="0"
android:layout_columnWeight="1"
android:layout_gravity="fill"
android:layout_row="0"
android:layout_rowWeight="1"
android:adjustViewBounds="true"
android:background="#android:color/transparent"
android:onClick="whiteNoiseTapped"
android:scaleType="fitXY"
android:text="White 1"
app:srcCompat="#drawable/whitenoise"
<ImageView>
<Button >
</Button>
</FrameLayout>

You can also do like following way
layout.xml to some extent like this...
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:background="#000"
tools:context="com.example.tistis.myapplication.MainActivity">
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/gridview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:numColumns="2"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
android:stretchMode="columnWidth"
android:gravity="center"
/>
and your ImageAdapter.java
following is the code. Please note it is a dirty way to code from
adapter rather one should inflate a view.
class ImageAdapter extends BaseAdapter {
private Context mContext;
public int screenHeight,screenWidth;
public ImageAdapter(Context c) {
mContext = c;
DisplayMetrics displaymetrics = new DisplayMetrics();
((Activity)c).getWindowManager().
getDefaultDisplay().getMetrics(displaymetrics);
screenHeight = displaymetrics.heightPixels;
screenWidth = displaymetrics.widthPixels;
}
public int getCount() {
return mThumbIds.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
public View getView(final int position,
View convertView, ViewGroup parent) {
ImageView imageView=null;
RelativeLayout frm;
SeekBar seekBar=null;
if (convertView == null) {
// if it's not recycled, initialize some attributes
frm= new RelativeLayout(mContext);
frm.setLayoutParams(new GridView.LayoutParams(screenWidth/2-(8*2+10),screenWidth/2-(8*2+10)));
frm.setPadding(8, 8, 8, 8);
frm.setBackgroundColor(Color.BLACK);
imageView = new ImageView(mContext);
imageView.setLayoutParams(
new FrameLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.MATCH_PARENT));
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.setBackgroundColor(Color.BLACK);
frm.addView(imageView);
imageView.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(mContext,
"Item position "+(position+1),
Toast.LENGTH_SHORT).show();
}
});
seekBar=new SeekBar(mContext);
seekBar.setLayoutParams(
new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT, 40));
RelativeLayout.LayoutParams lp=
(RelativeLayout.LayoutParams)
seekBar.getLayoutParams();
lp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
seekBar.setMax(15);
// seekBar.setIndeterminate(true);
ShapeDrawable thumb =
new ShapeDrawable(new OvalShape());
thumb.setIntrinsicHeight(80);
thumb.setIntrinsicWidth(30);
seekBar.setThumb(thumb);
seekBar.setProgress(1);
seekBar.setVisibility(View.VISIBLE);
seekBar.setBackgroundColor(Color.TRANSPARENT);
frm.addView(seekBar);
} else {
frm = (RelativeLayout) convertView;
}
if(imageView!=null)
imageView.setImageResource(mThumbIds[position]);
return frm;
}
// references to our images
private Integer[] mThumbIds = {
R.drawable.superman, R.drawable.superman,
R.drawable.superman, R.drawable.superman,
};
}

Related

Unable to Draw lines between two listviews or list of buttons in horizontal

I am trying to draw lines between two columns consists of 10 buttons in each column like in image showing below. I tried using linear layout.
private void createCHTDesign(int scenarios, int numberOfPlots, ArrayList<Plots> plotsArrayList) {
headingLayout.clear();
Log.d(TAG, "scenarios:" + scenarios);
Log.d(TAG, "headingsize:" + headingLayout.size());
for (int i = 0; i < scenarios; i++) {
LinearLayout linearLayout = new LinearLayout(mContext);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
if (i == 0) {
params.setMargins(0, 0, 0, 0);
} else {
params.setMargins(250, 0, 0, 0);
}
linearLayout.setOrientation(LinearLayout.VERTICAL);
linearLayout.setLayoutParams(params);
mainLayout.addView(linearLayout);
headingLayout.add(linearLayout);
Log.d(TAG, "count:" + mainLayout.getChildCount());
}
for (int i = 0; i < headingLayout.size(); i++) {
addButtons(headingLayout.get(i), i, numberOfPlots, plotsArrayList);
}
}
#SuppressLint("ClickableViewAccessibility")
private void addButtons(LinearLayout layout, int index, int numberOfPlots, ArrayList<Plots> plotsArrayList) {
TextView textView = new TextView(mContext);
LinearLayout.LayoutParams tvParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
textView.setLayoutParams(tvParams);
textView.setText(combinationNames.get(index));
textView.setTextSize(16);
layout.addView(textView);
for (int i = 0; i < numberOfPlots; i++) {
Button button = new Button(mContext);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(400, 150);
button.setLayoutParams(params);
button.setId(View.generateViewId());
button.setText(plotsArrayList.get(i).getMpValue() + "\n" + plotsArrayList.get(i).getYield());
button.setGravity(Gravity.CENTER_VERTICAL);
button.setPadding(15, 0, 0, 0);
button.setTextColor(Color.parseColor("#FFFFFF"));
button.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.right2x, 0);
GradientDrawable gradientDrawable = new GradientDrawable();
gradientDrawable.setColor(Color.parseColor(colors[i]));
gradientDrawable.setCornerRadius(10);
gradientDrawable.setStroke(20, Color.parseColor(colors[i]));
clickonArrow(button.getText().toString(), button);
button.setBackground(gradientDrawable);
layout.addView(button);
}
}
XML file:
<?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:orientation="vertical"
android:fitsSystemWindows="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="1"
android:layout_margin="10dp">
<androidx.appcompat.widget.AppCompatSpinner
android:id="#+id/spinner"
android:layout_width="wrap_content"
android:layout_weight="0.3"
android:layout_height="wrap_content"
android:spinnerMode="dropdown"
android:gravity="center"
style="#style/SpinnerTheme"
/>
<androidx.appcompat.widget.AppCompatSpinner
android:id="#+id/spinner2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.3"
android:spinnerMode="dropdown"
android:gravity="center"
style="#style/SpinnerTheme"/>
<androidx.appcompat.widget.AppCompatSpinner
android:id="#+id/spinner3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.3"
android:gravity="center"
android:spinnerMode="dropdown"
style="#style/SpinnerTheme" />
</LinearLayout>
<EditText
android:id="#+id/searchCht"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:drawableLeft="#drawable/ic_search"
android:layout_marginLeft="10dp"
android:hint="Search CHT"
android:backgroundTint="#android:color/black"
android:layout_marginRight="10dp"/>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="15dp"
android:layout_marginTop="15dp"
android:fillViewport="true"
android:scrollbars="horizontal">
<HorizontalScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="#+id/mainLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<!-- <com.sma.cht.chtcharacterization.view.MatchTheFollowingAttempted
android:id="#+id/match"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbarThumbHorizontal="#color/colorPrimary"
android:scrollbars="horizontal">
</com.sma.cht.chtcharacterization.view.MatchTheFollowingAttempted>
-->
</LinearLayout>
</HorizontalScrollView>
</ScrollView>
</LinearLayout>
Presently I am getting buttons in both columns but unable to draw lines either you can do this buttons stuff by using listview as well. can you please help me with this. Thanks in advance.
divide your cross line in two parts.
try the below code,
MainActivity.java
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerview=findViewById(R.id.recyclerview);
recyclerview.setLayoutManager(new LinearLayoutManager(this));
recyclerview.setAdapter(new SampleAdapter());
}
}
SampleAdapter.java
public class SampleAdapter extends RecyclerView.Adapter<SampleAdapter.MyViewHolder> {
ArrayList<String> list1;
ArrayList<String> list2;
public SampleAdapter() {
list1 = new ArrayList<>();
list2 = new ArrayList<>();
for (int i = 1; i <= 20; i++) {
list1.add("Left " + i);
list2.add("Right " + i);
}
}
#NonNull
#Override
public SampleAdapter.MyViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.recycle_item, viewGroup, false);
return new SampleAdapter.MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull SampleAdapter.MyViewHolder myViewHolder, int position) {
myViewHolder.buttonLeft.setText(list1.get(position));
myViewHolder.buttonRight.setText(list2.get(position));
//show partA image
if (position == 8) {
myViewHolder.imageview1.setVisibility(View.GONE);
myViewHolder.imageview2.setVisibility(View.VISIBLE);
}
//show partB image
if (position == 9) {
myViewHolder.imageview1.setVisibility(View.GONE);
myViewHolder.imageview3.setVisibility(View.VISIBLE);
}
}
#Override
public int getItemCount() {
return list1.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
Button buttonLeft, buttonRight;
ImageView imageview1, imageview2, imageview3;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
buttonLeft = itemView.findViewById(R.id.buttonLeft);
buttonRight = itemView.findViewById(R.id.buttonRight);
imageview1 = itemView.findViewById(R.id.imageview1);
imageview2 = itemView.findViewById(R.id.imageview2);
imageview3 = itemView.findViewById(R.id.imageview3);
}
}}
recycle_item.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="5">
<Button
android:id="#+id/buttonLeft"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2"
android:text="text" />
<ImageView
android:id="#+id/imageview1"
android:layout_width="0dp"
android:layout_height="30dp"
android:layout_gravity="center"
android:layout_weight="1"
android:background="#B3D4F3"
android:visibility="visible" />
<ImageView
android:id="#+id/imageview2"
android:layout_width="0dp"
android:layout_height="50dp"
android:layout_weight="1"
android:background="#drawable/image_a" android:visibility="gone" />
<ImageView
android:id="#+id/imageview3"
android:layout_width="0dp"
android:layout_height="50dp"
android:layout_weight="1"
android:background="#drawable/image_b android:visibility="gone" />
<Button
android:id="#+id/buttonRight"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2"
android:text="text" />
</LinearLayout>
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerview"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
image_a.png
image_b.png
output

How to make a gridview scrolling exactly the same as another gridview?

To display data in table layout with the first column frozen, the others can scroll horizontally, I have used 2 gridviews as below XML file content:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.gridviews.MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<GridView
android:id="#+id/gridViewID"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:columnWidth="50dp"
android:horizontalSpacing="1dp"
android:numColumns="1"
android:paddingTop="5dp"
android:stretchMode="columnWidth"
android:verticalSpacing="1dp" />
<HorizontalScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<GridView
android:id="#+id/gridViewDays"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:columnWidth="100dp"
android:horizontalSpacing="1dp"
android:numColumns="5"
android:paddingTop="5dp"
android:scrollbarStyle="outsideOverlay"
android:stretchMode="columnWidth"
android:verticalSpacing="1dp" />
</LinearLayout>
</HorizontalScrollView>
</LinearLayout>
</RelativeLayout>
and my code:
...
BaseAdapter adapterId = new BaseAdapter() {
#Override
public int getCount() {
return dataList.size();
}
#Override
public Object getItem(int position) {
return dataList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView textView = new TextView(context);
textView.setText(String.valueOf(dataList.get(position).Id));
textView.setLayoutParams(new GridView.LayoutParams(GridView.AUTO_FIT, 70));
return textView;
}
};
BaseAdapter adapterDays = new BaseAdapter() {
#Override
public int getCount() {
return dataList.size() * 5;
}
#Override
public Object getItem(int position) {
return dataList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView textView = new TextView(context);
int mod = position % 5;
int idx = position / 5;
switch (mod) {
case 0:
textView.setText(String.valueOf(dataList.get(idx).Mon));
break;
case 1:
textView.setText(String.valueOf(dataList.get(idx).Tue));
break;
case 2:
textView.setText(String.valueOf(dataList.get(idx).Wed));
break;
case 3:
textView.setText(String.valueOf(dataList.get(idx).Thu));
break;
case 4:
textView.setText(String.valueOf(dataList.get(idx).Fri));
break;
}
textView.setLayoutParams(new GridView.LayoutParams(GridView.AUTO_FIT, 70));
return textView;
}
};
gridViewID.setAdapter(adapterId);
gridViewDays.setAdapter(adapterDays);
// Horizontal scrolling of gridViewDays
LinearLayout.LayoutParams linearParams = (LinearLayout.LayoutParams) gridViewDays.getLayoutParams();
linearParams.width = 300;
gridViewDays.setLayoutParams(linearParams);
// Vertical scrolling...
gridViewID.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
int firstVisibleItem = view.getFirstVisiblePosition();
gridViewID.setSelection(firstVisibleItem);
gridViewDays.setSelection(firstVisibleItem * 5);
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
}
});
...
With these code, of course when I move my hand out of the screen, the gridViewDays gridview will have the same selection with the gridViewID as the image below:
However, when I keep my hand touch on the screen to scroll the gridViewID, the gridViewDays will look like the image below (it does not scroll while gridViewID is scrolling)
So, how can I make the gridViewDays gridview vertically scrolling the same as the gridViewID? I have also tried some methods such as smoothScrollToPosition, smoothScrollByOffset, smoothScrollToPositionFromTop... inside onScroll but they do not work
Update: although the answers (#vrundpurohit's and mine) below are working, however, I have found that the app has poor performance with big data (I mean when the data list has too many items).
use NonScrollGridView. and wrap both in single ScrollView
Here is code for NonScrollGridView..
public class NonScrollGridView extends GridView {
public NonScrollGridView(Context context) {
super(context);
}
public NonScrollGridView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public NonScrollGridView(Context context, AttributeSet attrs,
int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
#Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int heightMeasureSpec_custom = MeasureSpec.makeMeasureSpec(
Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, heightMeasureSpec_custom);
ViewGroup.LayoutParams params = getLayoutParams();
params.height = getMeasuredHeight();
}
}
EDIT:
Here is how you can do this.
<ScrollView android:id="#+id/scroll" ... >
<NonScrollGridView />
<RelativeLayout android:id="#+id/head1" ... >
<!-- header for 1st GridView -->
</RelativeLayout>
<HorizontalScrollView ... >
<HorizontalScrollView ... >
<NonScrollGridView />
<RelativeLayout android:id="#+id/head2" ... >
<!-- header for 1st GridView -->
</RelativeLayout>
</HorizontalScrollView>
</HorizontalScrollView>
</ScrollView>
Now for making both headers sticky.. do following.
scroll.getViewTreeObserver().addOnScrollChangedListener(
new ViewTreeObserver.OnScrollChangedListener() {
public void onScrollChanged() {
ViewCompat.setTranslationY(head1, who.getScrollY());
ViewCompat.setTranslationY(head2, who.getScrollY());
}
});
Happy Coding..
Thanks to #vrundpurohit comment, I have searched more in S.O and found
#dennisdrew's answer at
How to put GridView inside ScrollView
From there, I use the ExpandableHeightGridView class of #tacone at
Gridview height gets cut
to solve my issue.
My modified code:
...
final ExpandableHeightGridView gridViewID = (ExpandableHeightGridView) findViewById(R.id.gridViewID);
final ExpandableHeightGridView gridViewDays = (ExpandableHeightGridView) findViewById(R.id.gridViewDays);
gridViewID.setExpanded(true);
gridViewDays.setExpanded(true);
...
Layout file:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.gridviews.MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<com.example.gridviews.ExpandableHeightGridView
android:id="#+id/gridViewID"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:columnWidth="50dp"
android:horizontalSpacing="1dp"
android:numColumns="1"
android:stretchMode="columnWidth"
android:verticalSpacing="1dp" />
<HorizontalScrollView
android:id="#+id/horizontalScrollView"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<com.example.gridviews.ExpandableHeightGridView
android:id="#+id/gridViewDays"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:columnWidth="100dp"
android:horizontalSpacing="1dp"
android:numColumns="5"
android:scrollbarStyle="outsideOverlay"
android:stretchMode="columnWidth"
android:verticalSpacing="1dp" />
</LinearLayout>
</HorizontalScrollView>
</LinearLayout>
</ScrollView>
Thank you all!

First image appearing small in size and on top left corner in a viewpager when rotate the device

Hi in my application i am using the Viewpager with PagerAdapter. it contains n number of images. but when i rotate the device when viewpager is on first image then the image shift to top left corner and appears very small. please have a look in the attached image.
code which i am using
public class CustomViewPager extends ViewPager {
private final long SWITCH_TIME_INTERVAL = 5000;
public CustomViewPager(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
public CustomViewPager(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
postDelayed(mSwither, SWITCH_TIME_INTERVAL);
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int height = 0;
for (int i = 0; i < getChildCount(); i++) {
View child = getChildAt(i);
child.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
int h = child.getMeasuredHeight();
if (h > height)
height = h;
}
heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
/**
* this Runnable is use for automatically switching the view pager item.
* #author
*/
private Runnable mSwither = new Runnable() {
#Override
public void run() {
if( CustomViewPager.this.getAdapter() != null )
{
int count = CustomViewPager.this.getCurrentItem();
if( count == (CustomViewPager.this.getAdapter().getCount() - 1) )
{
count = 0;
}else
{
count++;
}
//Log.d(this.getClass().getName(), "Curent Page " + count + "");
CustomViewPager.this.setCurrentItem(count, true);
}
CustomViewPager.this.postDelayed(this, SWITCH_TIME_INTERVAL);
}
};
#Override
public boolean onTouchEvent(MotionEvent arg0) {
switch (arg0.getAction()) {
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP :
postDelayed(mSwither, SWITCH_TIME_INTERVAL);
break;
default:
removeCallbacks(mSwither);
break;
}
return super.onTouchEvent(arg0);
} }
//PagerAdapter onInstantiateItem code..
#Override
public Object instantiateItem(ViewGroup container, final int position) {
mImageFetcher.setLoadingImage(R.drawable.placeholder_tabportrait);
inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.test_fragment1, container, false);
description = (TextView) itemView.findViewById(R.id.description);
title = (TextView) itemView.findViewById(R.id.car_title);
published = (TextView) itemView.findViewById(R.id.date_data);
author = (TextView) itemView.findViewById(R.id.author);
jumbo_tron_image = (ImageView) itemView.findViewById(R.id.jumbo_imgae);
TrayItem trayItem = getData(position);
if (null != trayItem) {
if (trayItem.getType() != null) {
if (trayItem.getImages() != null) {
mImageFetcher.loadImage(trayItem.getImages().getWidget(),
jumbo_tron_image);
}
return itemView;
}
//xml code.
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="500dp"
android:background="#color/white">
<FrameLayout
android:id="#+id/main_container"
android:layout_width="match_parent"
android:layout_height="300dp"
android:layout_gravity="center_horizontal|center_vertical"
android:orientation="vertical"
>
<ImageView
android:id="#+id/jumbo_imgae"
android:layout_width="match_parent"
android:scaleType="fitXY"
android:layout_height="300dp"
/>
</FrameLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="#dimen/container_height"
android:layout_below="#+id/main_container">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:orientation="horizontal"
android:id="#+id/linearLayout2">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_alignParentLeft="true"
android:textStyle="bold"
android:layout_weight="0.5"
android:textColor="#color/black"
android:id="#+id/car_title"
android:maxLines="2"
android:ellipsize="end"
android:textSize="20sp"
android:text=" "/>
<ImageView
android:id="#+id/iv_add_test1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scaleType="centerCrop"
android:paddingTop="10dp"
android:src="#drawable/add_icon"
android:layout_centerVertical="true"
android:layout_toRightOf="#+id/car_title"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/linearLayout2"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:id="#+id/linearLayout3"
android:layout_marginTop="10dp"
android:orientation="horizontal">
<TextView
android:id="#+id/date_data"
android:layout_width="90dp"
android:layout_height="18dp"
android:text=""
android:textSize="13sp"
android:layout_gravity="left"
android:gravity="center"
android:textColor="#color/white"
android:background="#drawable/date_bg"/>
<TextView
android:id="#+id/author"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textSize="15sp"
android:layout_marginLeft="10dp"
android:textColor="#color/black"/>
</LinearLayout>
</LinearLayout>
</RelativeLayout> </RelativeLayout>

How do I center a GridView inside a fragment with viewpager

I have a Gridview inside a fragment of a ViewPager. I have 2x2 grid that I want to center on the parent, the ViewPager. It's displaying like this, only centering horizontally but not vertically My xml files are as follow.
This is the activity_main_menu.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/background"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="#+id/actionBar"
android:scaleType="centerCrop"
android:background="#drawable/home_01" />
<android.support.v4.view.ViewPager
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:layout_below="#+id/actionBar"
android:layout_above="#+id/buttonBar"
tools:context="com.excitingspace.areias_do_seixo.MainMenu" >
</android.support.v4.view.ViewPager>
<com.viewpagerindicator.CirclePageIndicator
android:id="#+id/titles"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="15dp"
android:layout_above="#+id/buttonBar"/>
</RelativeLayout>
And this is the fragment_main_menu.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.excitingspace.areias_do_seixo.MainMenu$PlaceholderFragment" >
<GridView
android:id="#+id/gridView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentTop="true"
android:columnWidth="150dp"
android:gravity="center"
android:listSelector="#android:color/transparent"
android:horizontalSpacing="10dp"
android:layout_centerInParent="true"
android:numColumns="2"
android:verticalSpacing="10dp" >
</GridView>
</RelativeLayout>
EDIT, adds the ImageAdapter used to populate the GridView:
public class ImageAdapter extends BaseAdapter {
private static int PADDING = 0;
private static int WIDTH = 0;
private static int HEIGHT = 0;
private Context mContext;
private List<Integer> mThumbIds;
private List<Integer> mThumbIds_highlighted;
public ImageAdapter(Context c, List<Integer> ids, List<Integer> ids_highlighted) {
mContext = c;
this.mThumbIds = ids;
this.mThumbIds_highlighted = ids_highlighted;
int baseWidth = 150;
int baseHeight = 150;
int basePading = 20;
float density = mContext.getResources().getDisplayMetrics().density;
if ((mContext.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_LARGE)
{
baseWidth = 200;
baseHeight = 200;
basePading = 20;
}
ImageAdapter.WIDTH = (int) (baseWidth * density + 0.5f);
ImageAdapter.HEIGHT = (int) (baseHeight * density + 0.5f);
ImageAdapter.PADDING = (int) (basePading * density + 0.5f);
}
#Override
public int getCount() {
return mThumbIds.size();
}
#Override
public Object getItem(int position) {
return null;
}
// Will get called to provide the ID that
// is passed to OnItemClickListener.onItemClick()
#Override
public long getItemId(int position) {
return mThumbIds.get(position);
}
// create a new ImageView for each item referenced by the Adapter
#SuppressWarnings("deprecation")
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
ImageView imageView = (ImageView) convertView;
StateListDrawable sld = new StateListDrawable();
Drawable draw1 = mContext.getResources().getDrawable(mThumbIds.get(position));
Drawable draw2 = mContext.getResources().getDrawable(mThumbIds_highlighted.get(position));
sld.addState(new int[] { android.R.attr.state_pressed }, draw2);
sld.addState(StateSet.WILD_CARD, draw1);
// if convertView's not recycled, initialize some attributes
if (imageView == null) {
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(WIDTH, HEIGHT));
imageView.setPadding(PADDING, PADDING, PADDING, PADDING);
// imageView.setScaleX();
}
imageView.setBackgroundDrawable(sld);
return imageView;
}
}
modify your fragment_main_menu.xml file like this
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.excitingspace.areias_do_seixo.MainMenu$PlaceholderFragment" >
<GridView
android:id="#+id/gridView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:columnWidth="150dp"
android:gravity="center_vertical"
android:listSelector="#android:color/transparent"
android:horizontalSpacing="10dp"
android:layout_centerInParent="true"
android:numColumns="2"
android:verticalSpacing="10dp" >
</GridView>
</RelativeLayout>

How to make a list of square buttons with autoresize?

I am developing an app that displays a page with a variable number of square buttons, like the second picture of "Square MIUI":
Square MIUI on APP store
I need displaying only three columns of square buttons, and make the entire list scrollable.
I'm trying first with plain XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ScrollView
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_gravity="center"
android:layout_weight="1.19"
android:orientation="horizontal" >
<TableLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center" >
<TableRow
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_weight="1" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:text="Title"/>
</TableRow>
<TableRow
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<!-- Icon buttons here -->
</TableRow>
</TableLayout>
</ScrollView>
<Button
android:layout_width="fill_parent"
android:layout_height="48dp"
android:text="Button" />
</LinearLayout>
For every button (4 TableRow of 3 buttons, images are square .png made with Eclipse icon generator)
EDIT: checked, icons of all screen densities are square
<Button
android:layout_margin="4dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="image"/>
but the buttons on my tablet are square, and on my phone are wider than tall (stretched on X-axis).
What I'm doing wrong?
TODO: code a variable button number.
Thanks in advance.
EDIT:
I tried this code:
private void squareButton() {
square(R.id.b1);
square(R.id.b2);
....
square(R.id.b<N>);
}
private void square(int id) {
ImageButton temp=(ImageButton) findViewById(id);
int l=temp.getWidth();
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int Measuredwidth = metrics.widthPixels;
l=(int) (Measuredwidth/4);
temp.setMaxWidth(l);
temp.setMaxHeight(l);
temp.setMinimumWidth(l);
temp.setMinimumHeight(l);
LayoutParams param = temp.getLayoutParams();
param.width = l;
param.height = l;
temp.setLayoutParams(param);
temp.requestLayout();
}
But I'm still getting weird buttons on phone (Gingerbread)...
I can't rely only on the auto-sized icons (too little on my tablet, too big on my phone)
EDIT:
I'm looking for a code that:
squares button
has user-definable width
works with Gingerbread
In my case, button_width = widthPixels/4;
Thank you in advance.
Implements you own square button class like this:
public class SquareButton extends Button {
public SquareButton(Context context) {
super(context);
}
public SquareButton(Context context, AttributeSet attrs) {
super(context, attrs);
}
public SquareButton(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
setMeasuredDimension(getMeasuredWidth(), getMeasuredWidth()); // Snap to width
}
}
Finally, I found a solution using GridView.
First, I follow the GridView tutorial
Then I got some code from other answers.
Now this code creates a scrollable and clickable big square icon list, resized according to screen size. When one icon is clicked, changes his image.
Thank you Lubos for your suggestion.
[main activity]
public class Grid extends Activity {
public boolean audio=true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_grid);
GridView gridview = (GridView) findViewById(R.id.gridview);
gridview.setAdapter(new ImageAdapter(this));
// load icons on grid
ImageAdapter.loadImages(new Integer[] {
R.drawable.ic_blu_voice_on,
R.drawable.ic_blu_help,
R.drawable.ic_blu_save,
R.drawable.ic_blu_load
});
gridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View imgView, int position, long id) {
ImageView image=(ImageView) imgView;
switch (position) {
case 0:
// switch voice icon on/off when clicked
image.setImageResource(voice());
break;
}
Toast.makeText(Grid.this, "" + position, Toast.LENGTH_SHORT).show();
}
});
}
private int voice() {
audio=!audio;
if (audio) return R.drawable.ic_blu_voice_on;
return R.drawable.ic_blu_voice_off;
}
}
[imageadapter.java]
public class ImageAdapter extends BaseAdapter {
private Context mContext;
// reference to images (dummy)
private static Integer[] mThumbIds = {0,0};
private float px;
public ImageAdapter(Context c) {
mContext = c;
//Calculation of ImageView Size - density independent.
Resources r = Resources.getSystem();
px = r.getDisplayMetrics().widthPixels;
px=px/3;
}
public int getCount() {
return mThumbIds.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
public static void setImage(int position, int id) {
mThumbIds[position]=id;
}
public static void loadImages(Integer[] images) {
mThumbIds = images;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) { // if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams((int)px, (int)px));
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.setPadding(8, 8, 8, 8);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(mThumbIds[position]);
return imageView;
}
}
[activity_grid.xml]
<RelativeLayout xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_gravity="center_horizontal"
android:orientation="vertical"
tools:context="${packageName}.${activityClass}">
<LinearLayout
android:id="#+id/LinearLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center_horizontal"
android:orientation="vertical"
tools:context="${relativePackage}.${activityClass}" >
<TextView
android:id="#+id/testo1"
android:layout_width="fill_parent"
android:layout_height="48dp"
android:gravity="center_horizontal"
android:text="#string/hello_world"
android:textSize="30sp" />
<GridView
android:id="#+id/gridview"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:columnWidth="120dp"
android:gravity="center"
android:numColumns="auto_fit"
android:stretchMode="spacingWidthUniform">
</GridView>
<Button
android:id="#+id/button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/hello_world"
android:textSize="30sp" />
</LinearLayout>
</RelativeLayout>

Categories

Resources