Please assist me with implementing MP Line Chart in ListView; it works good in recycler view, however it loses its size as I add more than 5 items.
Because of the scroll view, I'm using an expanded listView to reduce issues, yet the chart looks like this.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_margin="10sp"
android:orientation="vertical"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="20sp"
android:textStyle="bold"
android:textColor="#color/black"
android:text="#string/most_active_stocks"/>
<LinearLayout
android:visibility="visible"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_gravity="center"
android:gravity="center"
android:layout_margin="10sp">
<Button
android:layout_width="wrap_content"
android:textSize="10sp"
android:layout_gravity="center"
android:layout_height="40dp"
android:layout_margin="5dp"
android:background="#drawable/virtualtrading_button"
android:text="Volume"
android:gravity="center"
android:textColor="#color/black" />
<Button
android:layout_width="wrap_content"
android:layout_height="40dp"
android:textSize="10sp"
android:layout_gravity="center"
android:layout_margin="5dp"
android:background="#drawable/virtualtrading_button"
android:text="%Turnover"
android:gravity="center"
android:textColor="#color/black" />
<Button
android:layout_width="wrap_content"
android:layout_height="40dp"
android:textSize="10sp"
android:layout_margin="5dp"
android:layout_gravity="center"
android:background="#drawable/virtualtrading_button"
android:text="Range"
android:gravity="center"
android:textColor="#color/black" />
</LinearLayout>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<com.catalyst.maksl.Components.ExpandableHeightListView
android:id="#+id/moverlist"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:drawSelectorOnTop="false"
android:fadingEdge="vertical"
android:divider="#android:color/transparent"
android:dividerHeight="5dp"
android:fitsSystemWindows="true"
android:listSelector="#00000000"
android:scrollbars="none"
android:smoothScrollbar="true" />
</RelativeLayout>
</LinearLayout>
ExpandableListView Class
public class ExpandableHeightListView extends ListView {
boolean expanded = false;
public ExpandableHeightListView(Context context)
{
super(context);
}
public ExpandableHeightListView(Context context, AttributeSet attrs)
{
super(context, attrs);
}
public ExpandableHeightListView(Context context, AttributeSet attrs,int defStyle)
{
super(context, attrs, defStyle);
}
public boolean isExpanded()
{
return expanded;
}
#Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
// HACK! TAKE THAT ANDROID!
if (isExpanded())
{
// Calculate entire height by providing a very large height hint.
// But do not use the highest 2 bits of this integer; those are
// reserved for the MeasureSpec mode.
int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, 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;
}
}
adapter class :
public class MostActiveStocksAdapter extends BaseAdapter {
private static LineDataSet set1;
public static Drawable drawablePositive = ContextCompat.getDrawable(Logs.globalContext, R.drawable.graph_green_bg);
public static Drawable drawable_negative = ContextCompat.getDrawable(Logs.globalContext, R.drawable.graph_bg);
Context context;
private Double changePercentage;
ArrayList<String> arrayList = new ArrayList<String>();
LayoutInflater mInflater = null;
private ViewHolder holder;
public ArrayList<Entry> values;
public LineData data;
public MostActiveStocksAdapter(Context context, ArrayList<String> arrayList) {
this.context = context;
this.arrayList = arrayList;
mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return arrayList.size();
}
#Override
public Object getItem(int position) {
return arrayList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = mInflater.inflate(R.layout.most_active_stocks_listitem, null);
holder = new ViewHolder();
holder.moverSymbolName = (TextView) convertView.findViewById(R.id.moversymbolName);
holder.moverScripName = (AutoResizeTextView) convertView.findViewById(R.id.moversmainSymbolName);
holder.moverLastTradePrice = (TextView) convertView.findViewById(R.id.moverslastTradePrice);
holder.moverchange = (AutoResizeTextView) convertView.findViewById(R.id.moversindexChange);
holder.moverMarket = (TextView) convertView.findViewById(R.id.moverssymbolMarket);
holder.sector = convertView.findViewById(R.id.movertextSector);
holder.nameIcon = convertView.findViewById(R.id.moverNameicon);
holder.masLineChart = convertView.findViewById(R.id.moversgraph);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
ScripBean scripBean = Logs.allScripBean.get(arrayList.get(position));
MostActiveStockMarketFeedBean marketFeedBean = Logs.mostActiveStockMarketFeedBeanHashMap.get(arrayList.get(position));
if (marketFeedBean != null) {
changePercentage = marketFeedBean.getChange() / (marketFeedBean.getLastTradePrice() - marketFeedBean.getChange()) * 100;
holder.moverScripName.setText(marketFeedBean.getScrip());
holder.moverSymbolName.setText(marketFeedBean.getScripName());
holder.sector.setText(scripBean.getSectorName());
holder.nameIcon.setText(marketFeedBean.getScrip().substring(0,1));
holder.moverLastTradePrice.setText(Logs.priceFormat.format(marketFeedBean.getLastTradePrice()).replace("-", ""));
setData(5,3);
customiseChart();
if(marketFeedBean.getChange() != 0.0) {
if (Logs.priceFormat.format(changePercentage).contains("-")) {
holder.moverLastTradePrice.setBackground(context.getResources().getDrawable(R.drawable.bg_negativecell));
}
else
{
holder.moverLastTradePrice.setBackground(context.getResources().getDrawable(R.drawable.bg_positivecell));
}
holder.moverchange.setText(marketFeedBean.getChange() + " " + "(" + Logs.priceFormat.format(changePercentage).replace("-", "") + "%)");
}
else
{
holder.moverchange.setText("(0.00%)");
}
}
else {
String sm = arrayList.get(position);
holder.moverScripName.setText(sm.split("\\:", -1)[0]);
holder.moverMarket.setText(sm.split("\\:", -1)[1]);
holder.moverSymbolName.setText("");
holder.moverLastTradePrice.setText("0.00");
holder.moverchange.setText("0.00");
}
return convertView;
}
private void setData(int count, float range) {
values = new ArrayList<>();
for (int i = 0; i < count; i++) {
float val = (float) (Math.random() * range) - 30;
values.add(new Entry(i, val));
}
set1 = new LineDataSet(values, "DataSet 1");
set1.setDrawCircles(false);
set1.setDrawFilled(true);
set1.setLineWidth(1f);
set1.setColor(Color.GREEN);
set1.setMode(LineDataSet.Mode.CUBIC_BEZIER);
set1.setDrawFilled(true);
set1.setFillDrawable(drawablePositive);
set1.setFillFormatter(new IFillFormatter() {
#Override
public float getFillLinePosition(ILineDataSet dataSet, LineDataProvider dataProvider) {
return holder.masLineChart.getAxisLeft().getAxisMinimum();
}
});
ArrayList<ILineDataSet> dataSets = new ArrayList<>();
dataSets.add(set1);
data = new LineData(dataSets);
holder.masLineChart.setData(data);
}
private void customiseChart()
{
holder.masLineChart.getDescription().setEnabled(false);
holder.masLineChart.setDrawGridBackground(false);
holder.masLineChart.setDragEnabled(false);
holder.masLineChart.getLegend().setEnabled(false);
holder.masLineChart.setScaleEnabled(true);
holder.masLineChart.setScaleYEnabled(false);
holder.masLineChart.setScaleXEnabled(true);
holder.masLineChart.setDrawGridBackground(false);
holder.masLineChart.getXAxis().setEnabled(false);
holder.masLineChart.getLineData().setDrawValues(false);
holder.masLineChart.getXAxis().setDrawGridLines(false);
holder.masLineChart.getXAxis().setDrawAxisLine(false);
holder.masLineChart.getAxisLeft().setDrawGridLines(false);
holder.masLineChart.getAxisRight().setDrawGridLines(false);
holder.masLineChart.getAxisRight().setDrawZeroLine(true);
holder.masLineChart.getAxisLeft().setDrawZeroLine(true);
holder.masLineChart.getAxisRight().setDrawLabels(false);
holder.masLineChart.getAxisLeft().setDrawLabels(false);
holder.masLineChart.getAxisLeft().setEnabled(false);
holder.masLineChart.getAxisRight().setEnabled(true);
holder.masLineChart.getAxisRight().setZeroLineColor(Color.BLACK);
holder.masLineChart.getAxisRight().setAxisLineColor(Color.BLACK);
holder.masLineChart.setMaxHighlightDistance(150);
holder.masLineChart.setViewPortOffsets(0, 0, 0, 0);
holder.masLineChart.setTouchEnabled(false);
holder.masLineChart.setPinchZoom(false);
}
private class ViewHolder {
TextView moverSymbolName;
TextView moverMarket;
AutoResizeTextView moverScripName;
TextView moverLastTradePrice;
AutoResizeTextView moverchange;
TextView sector;
TextView nameIcon;
LineChart masLineChart;
}
P.S: this ListView is in fragment.
Related
I want to make an internal grid view(room) added by clicking the button on the external recycler view(floor). but Null pointer extension occurs in onBindViewHolder. please help me
public class FloorAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements OnFloorItemClickListener {
OnFloorItemClickListener listener;
static public ArrayList<FloorData> floors;
private Context context;
private LayoutInflater layoutInflater;
private OnItemClickListener mListener = null;
public FloorAdapter(ArrayList<FloorData> floors, Context context) {
this.floors = floors;
this.context = context;
this.layoutInflater = LayoutInflater.from(context);
}
public interface OnItemClickListener{
void onItemClick(View v, int pos);
}
public void setOnItemClickListener(OnItemClickListener listener) {
this.mListener = listener ;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = layoutInflater.inflate(R.layout.signle_floor, parent, false);
return new GridViewHolder(view);
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
((GridViewHolder)holder).recyclerView.setAdapter(new RoomAdapter(context, floors.get(position).rooms));
((GridViewHolder)holder).recyclerView.setLayoutManager(new GridLayoutManager(context, 2));
((GridViewHolder)holder).recyclerView.setHasFixedSize(true);
((GridViewHolder)holder).tvFloorNum.setText(String.valueOf(floors.get(position).floorNum));
}
#Override
public int getItemCount() {
return floors.size();
}
#Override public void onItemClick(RecyclerView.ViewHolder holder, View view, int position) {
if(listener != null){
listener.onItemClick(holder,view,position);
}
}
#Override
public int getItemViewType(int position) {
return floors.get(position).id;
}
public class GridViewHolder extends RecyclerView.ViewHolder {
RecyclerView recyclerView;
TextView tvFloorNum;
Button btnPlusRoom;
public GridViewHolder(View itemView) {
super(itemView);
recyclerView = itemView.findViewById(R.id.rvRooms);
tvFloorNum = itemView.findViewById(R.id.tvRoomNumber);
btnPlusRoom = (Button)itemView.findViewById(R.id.btnPlusRoom);
btnPlusRoom.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v)
{
int pos = getAdapterPosition();
if (pos != RecyclerView.NO_POSITION)
{
if(mListener != null){
mListener.onItemClick(v, pos);
}
}
}
});
}
}
}
public class RoomAdapter extends RecyclerView.Adapter<RoomAdapter.CustomViewHolder> {
private Context context;
private ArrayList<RoomData> rooms;
private LayoutInflater inflater;
public RoomAdapter(Context context, ArrayList<RoomData> rooms) {
this.context = context;
this.rooms = rooms;
this.inflater = LayoutInflater.from(context);
}
#Override
public CustomViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view;
view = inflater.inflate(R.layout.single_room, parent, false);
return new CustomViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull CustomViewHolder holder, int position) {
RoomData room = rooms.get(position);
holder.tvRoomNum.setText(String.valueOf(room.roomNum));
}
#Override
public int getItemCount() {
return rooms.size();
}
public static class CustomViewHolder extends RecyclerView.ViewHolder {
public TextView tvRoomNum;
public CustomViewHolder(View itemView) {
super(itemView);
tvRoomNum = (TextView) itemView.findViewById(R.id.tvRoomNumber);
}
}
}
public class RoomActivity extends AppCompatActivity {
private RecyclerView rvFloor;
private FloorAdapter floorAdapter;
public ArrayList<FloorData> globalfloors;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_room);
globalfloors = prepareData();
rvFloor = findViewById(R.id.rvFloors);
floorAdapter = new FloorAdapter(globalfloors, RoomActivity.this);
LinearLayoutManager manager = new LinearLayoutManager(RoomActivity.this);
rvFloor.setLayoutManager(manager);
rvFloor.setAdapter(floorAdapter);
floorAdapter.setOnItemClickListener(new FloorAdapter.OnItemClickListener() {
#Override
public void onItemClick(View v, int position) {
FloorData floor = globalfloors.get(position);
RoomData newRoom = new RoomData();
floor.finalRoomNum++;
newRoom.roomNum = floor.finalRoomNum;
floor.rooms.add(newRoom);
rvFloor.setAdapter(floorAdapter);
}
});
}
private ArrayList<FloorData> prepareData() {
ArrayList<FloorData> floors = new ArrayList<FloorData>();
//첫번째 subject 추가
FloorData floor1 = new FloorData();
floor1.floorNum = 1;
RoomData room101 = new RoomData();
room101.roomNum = 101;
RoomData room102 = new RoomData();
room102.roomNum = 102;
RoomData room103 = new RoomData();
room103.roomNum = 103;
floor1.finalRoomNum = 103;
floor1.rooms.add(room101);
floor1.rooms.add(room102);
floor1.rooms.add(room103);
floors.add(floor1);
FloorData floor2 = new FloorData();
floor2.floorNum = 2;
floor2.finalRoomNum = 200;
floors.add(floor2);
return floors;
}
}
activity_room
<?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"
tools:context=".tools.RewardActivity"
android:orientation="vertical">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolBar_room"
android:layout_width="match_parent"
android:layout_gravity="center"
android:layout_height="60dp"
android:background="#color/colorPrimaryDark"
app:title="호실 등록"
android:theme="#style/ToolbarTheme" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/rvFloors"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
single_floor
<?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="wrap_content"
android:orientation="vertical">
<LinearLayout
android:orientation="vertical"
android:background="#FFFFFF"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="15dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<TextView
android:id="#+id/tvFloorNum"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:textSize="30dp"
android:textColor="#000000" />
<Button
android:id="#+id/btnPlusRoom"
android:layout_width="40dp"
android:layout_height="40dp"
android:text="+"
android:textSize="30dp"
android:layout_marginTop="10dp"
android:background="#color/colorPrimaryDark"/>
</LinearLayout>
<androidx.recyclerview.widget.RecyclerView
android:columnCount="5"
android:id="#+id/rvRooms"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
</LinearLayout>
single_room
<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="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="2dp">
<TextView
android:id="#+id/tvRoomNumber"
android:layout_width="70dp"
android:layout_height="70dp"
android:layout_marginBottom="5dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="5dp"
android:ellipsize="end"
android:singleLine="true"
android:background="#color/colorAccent"
android:gravity="center"
android:textSize="30dp"
/>
</LinearLayout>
</LinearLayout>
error message describes "java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at com.eos.parcelnoticemanager.tools.FloorAdapter.onBindViewHolder"
The GridViewHolder inside your FloorAdapter is pointing to the wrong XML Id tag for the TextView that's why it's throwing NullPointerException
Change this in your GridViewHolder
tvFloorNum = itemView.findViewById(R.id.tvRoomNumber);
to this
tvFloorNum = itemView.findViewById(R.id.tvFloorNumber);
Then it should work
I want Help to overlay a play icon on top of every grid item, if it contains video.Here is my Layout File of GridView. I was Trying to do, but i was not able to wire up all things.
Ps :- I am Newbie
<FrameLayout
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:padding="2dp"
tools:context="com.techx.storysaver.ImageFragment">
<GridView
android:id="#+id/grid_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:horizontalSpacing="2dp"
android:listSelector="#drawable/griditem_selector"
android:numColumns="2"
android:drawSelectorOnTop="true"
android:stretchMode="columnWidth"
android:verticalSpacing="2dp" />
</FrameLayout>
Here is my ImageAdapter
public class ImageAdapter extends BaseAdapter {
private Context context;
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Pictures";
File f = new File(path);
File file[] = f.listFiles();
public ImageAdapter(Context c) {
context = c;
}
#Override
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
}
#Override
public int getCount() {
return file.length;
}
#Override
public Object getItem(int position) {
return file[position];
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Arrays.sort(file, LastModifiedFileComparator.LASTMODIFIED_REVERSE);
final String path = file[position].getAbsolutePath();
CheckableLayout l;
ImageView i;
if (convertView == null) {
i = new ImageView(context);
i.setScaleType(ImageView.ScaleType.CENTER_CROP);
int widthSize = getScreenWidth();
widthSize = widthSize / 2;
widthSize = widthSize - 8;
int heightSize = getScreenHeight();
heightSize = heightSize / 3;
heightSize = heightSize - 10;
i.setLayoutParams(new ViewGroup.LayoutParams(widthSize, heightSize));
i.setPadding(8, 8, 8, 8);
l = new CheckableLayout(context);
l.setLayoutParams(new GridView.LayoutParams(GridView.LayoutParams.WRAP_CONTENT, GridView.LayoutParams.WRAP_CONTENT));
l.addView(i);
} else {
l = (CheckableLayout) convertView;
i = (ImageView) l.getChildAt(0);
}
if (path.endsWith(".jpg") || path.endsWith(".jpeg") || path.endsWith(".png")) {
Glide
.with(context)
.load(file[position])
.into(i);
}
if (path.endsWith(".mp4")) {
Glide
.with(context)
.load(file[position])
.into(i);
}
return l;
}
public class CheckableLayout extends FrameLayout implements Checkable {
private boolean mChecked;
public CheckableLayout(Context context) {
super(context);
}
#SuppressWarnings("deprecation")
public void setChecked(boolean checked) {
mChecked = checked;
setBackgroundDrawable(checked ? getResources().getDrawable(R.drawable.item_selector) : null);
}
public boolean isChecked() {
return mChecked;
}
public void toggle() {
setChecked(!mChecked);
}
}
public static int getScreenWidth() {
return Resources.getSystem().getDisplayMetrics().widthPixels;
}
public static int getScreenHeight() {
return Resources.getSystem().getDisplayMetrics().heightPixels;
}
}
1. Create an layout XML for your GridView Item.
grid_item.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:card_view="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/tools"
android:id="#+id/card_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
card_view:cardCornerRadius="4dp"
card_view:cardUseCompatPadding="false"
card_view:cardPreventCornerOverlap="false">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/image"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:scaleType="centerCrop"
android:src="#drawable/sample_1" />
<ImageView
android:id="#+id/icon_play"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:src="#drawable/icon_play"/>
<TextView
android:id="#+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/image"
android:padding="8dp"
android:background="#CCFFFFFF"
android:text="This is simple title"
android:textColor="#000000" />
</RelativeLayout>
</android.support.v7.widget.CardView>
2. Use grid_item.xml from your adapter getView() method for each item:
#Override
public View getView(int pos, View convertView, ViewGroup parent)
{
Arrays.sort(file, LastModifiedFileComparator.LASTMODIFIED_REVERSE);
final String path = file[position].getAbsolutePath();
if(convertView == null)
{
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.grid_item, null);
}
ImageView imageView = (ImageView) convertView.findViewById(R.id.image);
ImageView iconPlay= (ImageView) convertView.findViewById(R.id.icon_play);
TextView textTitle= (TextView) convertView.findViewById(R.id.title);
// Image
if (path.endsWith(".jpg") || path.endsWith(".jpeg") || path.endsWith(".png")) {
Glide
.with(context)
.load(file[position])
.into(imageView);
// Hide play icon
iconPlay.setVisibility(View.GONE);
}
// Video
if (path.endsWith(".mp4")) {
Glide
.with(context)
.load(file[position])
.into(imageView);
// Show play icon
iconPlay.setVisibility(View.VISIBLE);
}
return convertView;
}
OUTPUT:
Hope this will help~
I have a gridview (expandableHeightGridView) that lays within a scrollView.
When the gridview contains 4 pictures it works fine. However, if I add 2 more, it becomes unresponsive or very laggy. A log message appears saying that I am doing too much work on the main thread. I have tried to create asyncTask to handle some of the work but nothing seems to work.
This is my Main class:
public class MainActivity extends GeneralActivity {
private ExpandableHeightGridView gv;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
gv = (ExpandableHeightGridView) findViewById(R.id.MainActivity_gv);
gv.setExpanded(true);
GridAdapter adapter = new GridAdapter(this);
gv.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
public void onClickDestaques1(View v) {
Log.v("LOG", "numero 1");
}
public void onClickDestaques2(View v){
Log.v("LOG", "numero 2");
}
public void onClickDestaques3(View v){
Log.v("LOG", "numero 3");
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
Intent intent;
switch (item.getItemId()) {
case R.id.pontos:
intent = new Intent(MainActivity.this, HistoricoDePontosActivity.class);
MainActivity.this.startActivity(intent);
return true;
case R.id.info:
intent = new Intent(MainActivity.this, AlterarInfoActivity.class);
MainActivity.this.startActivity(intent);
return true;
case R.id.senha:
intent = new Intent(MainActivity.this, AlterarSenhaActivity.class);
MainActivity.this.startActivity(intent);
return true;
case R.id.config:
intent = new Intent(MainActivity.this, ConfiguracoesActivity.class);
MainActivity.this.startActivity(intent);
return true;
case R.id.ajuda:
intent = new Intent(MainActivity.this, AjudaActivity.class);
MainActivity.this.startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return true;
}
}
The Main xml class:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="#dimen/activity_padding" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/main_ll1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="CPF: 947665665-45"
android:textColor="#846248"
android:textSize="15sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Saldo: 150 pts"
android:textColor="#153515"
android:textSize="15sp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Bem-vindo, GUSTAVO"
android:textSize="25sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Aqui esta escrito algo interessante mas totalmente irrelevante." />
</LinearLayout>
<com.br.ExpandableHeightGridView
android:id="#+id/MainActivity_gv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:horizontalSpacing="10dp"
android:isScrollContainer="false"
android:numColumns="2"
android:stretchMode="columnWidth"
android:verticalSpacing="10dp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:background="#0266c8"
android:gravity="center"
android:text="Destaques"
android:textColor="#ffffff"
android:textSize="25sp" >
</TextView>
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/activity_padding"
android:adjustViewBounds="true"
android:onClick="onClickDestaques1"
android:scaleType="centerCrop"
android:src="#drawable/icone1land" />
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/activity_padding"
android:onClick="onClickDestaques2"
android:adjustViewBounds="true"
android:scaleType="centerCrop"
android:src="#drawable/icone1land" />
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/activity_padding"
android:onClick="onClickDestaques3"
android:adjustViewBounds="true"
android:scaleType="centerCrop"
android:src="#drawable/icone1land" />
<TextView
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_marginTop="#dimen/activity_padding"
android:textSize="200sp" >
</TextView>
</LinearLayout>
</ScrollView>
This is the GridAdapter class:
class GridAdapter extends BaseAdapter {
private Context context;
private ArrayList<Item> items = new ArrayList<Item>();
private LayoutInflater inflater;
public GridAdapter(Context context) {
inflater = LayoutInflater.from(context);
this.context = context;
items.add(new Item(R.drawable.icone1land, JunteActivity.class));
items.add(new Item(R.drawable.icone2land, TroqueActivity.class));
items.add(new Item(R.drawable.icone3land, DeliveryActivity.class));
items.add(new Item(R.drawable.icone4land, EventosActivity.class));
items.add(new Item(R.drawable.icone5land, ReservasActivity.class));
items.add(new Item(R.drawable.icone6land, ContatosActivity.class));
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int i) {
return items.get(i);
}
#Override
public long getItemId(int i) {
return items.get(i).drawableId;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
ViewHolder holder;
if(view == null) {
view = inflater.inflate(R.layout.activity_inflater_gridview, viewGroup, false);
holder = new ViewHolder();
holder.img = (ImageView) view.findViewById(R.id.picture);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
final Item item = (Item) getItem(i);
holder.img = (ImageView) view.findViewById(R.id.picture);
holder.img.setImageResource(item.drawableId);
holder.img.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, item.activityClass);
context.startActivity(intent);
}
});
return view;
}
static class ViewHolder {
ImageView img;
}
}
The expandableGrid class:
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) {
// HACK! TAKE THAT ANDROID!
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;
}
}
and the squareImageView class:
public class SquareImageView extends ImageView {
public SquareImageView(Context context) {
super(context);
}
public SquareImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public SquareImageView(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
}
}
Please help me. I am stuck on this problem for a while. Couldnt solve my problem with existing questions on the matter, thus I need a more customisable answer. Thanks you!
The images were too big and for that reason I was getting these error messages. I resized my images and suddenly everything started to work just fine! Thanks #tyczj for your comment
I have a gridView witch contains a group of images with two columns, what I want to do is to put a title for a group of images.
Now I can do that but the problem that title is that the title is only in one column and the second column is always empty, how can I put the title in the two columns?
Here is my adapter:
public class MultimediaPhotosAdapter extends BaseAdapter {
private Context mContext;
private List<ImagesDto> imagesDto = new ArrayList<ImagesDto>();
ImagesFlickrDto imagesFlickrDto;
final String formatImage = ImagesNameFormat.FORMAT_IMAGE_DEFAULT.getImagesNameFormat();
ImagesFormatsDto currentImageFormatToDisplay;
GridView gridViewImages;
public MultimediaPhotosAdapter(Context context, GridView gridViewImages) {
this.gridViewImages = gridViewImages;
this.mContext = context;
}
#Override
public int getCount() {
return imagesDto.size();
}
#Override
public Object getItem(int position) {
return imagesDto.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View itemView = null;
HolderElementGridView holderElementGridView;
ImagesDto currentImage = imagesDto.get(position);
if(convertView == null) {
holderElementGridView = new HolderElementGridView();
itemView = View.inflate(mContext,R.layout.item_multimedia_photo,null);
holderElementGridView.image = (NetworkImageView) itemView.findViewById(R.id.imageView);
holderElementGridView.title = (TextView) itemView.findViewById(R.id.title);
itemView.setTag(holderElementGridView);
}
else {
itemView = convertView;
holderElementGridView = (HolderElementGridView)itemView.getTag();
}
if(imagesDto.get(position).isFirstElementOfCategorie()){
holderElementGridView.image.setVisibility(View.GONE);
holderElementGridView.title.setVisibility(View.VISIBLE);
holderElementGridView.title.setText(currentImage.getTitle());
}
else if(imagesDto.get(position).getUrl()!=null){
holderElementGridView.image.setVisibility(View.VISIBLE);
holderElementGridView.title.setVisibility(View.GONE);
holderElementGridView.image.setImageUrl(StringFormat.getUrlImage(mContext, currentImage.getUrl(), currentImageFormatToDisplay.getSuffix(), currentImageFormatToDisplay.getExtension()),VolleySingleton.getInstance(mContext).getImageLoader());
holderElementGridView.image.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
DrawerLayoutInterface screenInterface=(DrawerLayoutInterface)mContext;
if(screenInterface!=null)
screenInterface.showDiaporama(imagesFlickrDto,position);
}
});
}
// column near title is empty
else{
holderElementGridView.image.setVisibility(View.VISIBLE);
holderElementGridView.title.setVisibility(View.GONE);
}
return itemView;
}
public void update(ImagesFlickrDto imagesFlickrDto){
this.imagesFlickrDto = imagesFlickrDto;
this.imagesDto = imagesFlickrDto.getListImages();
AdministrerImagesSA administrerImages = new AdministrerImagesSAImpl();
currentImageFormatToDisplay = administrerImages.getFormatByProriete(imagesFlickrDto.getImagesFormatsDto(), formatImage);
}
class HolderElementGridView{
NetworkImageView image;
TextView title;
}
}
item_multimedia_photo.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:geekui="http://schemas.android.com/apk/res-auto"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<com.netcosports.anderlecht.activity.utils.TypefaceTextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="#dimen/text_size_item_menu"
android:visibility="gone"
android:layout_marginLeft="5dp"
geekui:customTypeface="fonts/DIN-Regular.otf" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<com.android.volley.toolbox.NetworkImageView
android:id="#+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginRight="5dp"
android:layout_marginLeft="5dp"
android:src="#drawable/ic_launcher" >
</com.android.volley.toolbox.NetworkImageView>
</LinearLayout>
</LinearLayout>
I'm new to programming for Android (and Java) and have managed to get a custom adapter working, but am stuck on how to update textViews inside of it. Below you will see my score_save function with the code I want, but I'm not sure how to apply this to all rows of my adapter at once.
public class MainActivity extends Activity {
private ListView listView1;
private int currentPlayer;
private int currentScore;
ArrayList<Integer> allScoreChange = new ArrayList<Integer>();
ArrayList<Integer> allScore = new ArrayList<Integer>();
Button button_add, button_add_big, button_sub, button_sub_big,
button_add_num, button_save;
TextView name;
TextView score;
TextView scoreChange;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Score score_data[] = new Score[] { new Score("NameA"),
new Score("NameB"), new Score("NameC"), new Score("NameD"),
new Score("NameE") };
//sets score lists to 0
for (int i = 0; i < 5; i++) {
allScoreChange.add(0);
allScore.add(0);
}
ScoreAdapter adapter = new ScoreAdapter(this,
R.layout.listview_item_row, score_data);
listView1 = (ListView) findViewById(R.id.listView1);
listView1.setAdapter(adapter);
listView1.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
currentScore = allScoreChange.get(position);
// Gets fields from current row
score = (TextView) view.findViewById(R.id.txtScore);
scoreChange = (TextView) view.findViewById(R.id.txtScoreChange);
currentPlayer = position;
}
});
button_save.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
score_save();
}
});
}
public void score_save() {
// this needs to go through all rows of listview
currentPlayer = 0;
// update array with new score
allScore.set(currentPlayer, allScore.get(currentPlayer)
+ allScoreChange.get(currentPlayer));
// display new score
score.setText(allScore.get(currentPlayer));
// reset score change to zero
allScoreChange.set(currentPlayer, 0);
// display score change as blank
scoreChange.setText("");
}
}
Here's the XML for the row, I want to update txtScoreChange and txtScore with the values out of the allScoreChange and allScore ArrayLists. I cut out the code that defines these lists, in case you're wondering.
<?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="fill_parent"
android:orientation="horizontal"
android:padding="10dp" >
<TextView
android:id="#+id/txtTitle"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginBottom="5dp"
android:layout_marginTop="5dp"
android:layout_weight="70"
android:text="Name"
android:textColor="#000000"
android:textSize="22sp"
android:textStyle="bold" />
<TextView
android:id="#+id/txtScoreChange"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginBottom="5dp"
android:layout_marginRight="5dp"
android:layout_marginTop="5dp"
android:layout_weight="15"
android:textColor="#ff0000"
android:textSize="22sp"
android:gravity="right" />
<TextView
android:id="#+id/txtScore"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginBottom="5dp"
android:layout_marginRight="5dp"
android:layout_marginTop="5dp"
android:layout_weight="15"
android:text="1"
android:textColor="#666666"
android:textSize="22sp"
android:gravity="right" />
Here's my adapter:
public class ScoreAdapter extends ArrayAdapter<Score>{
Context context;
int layoutResourceId;
Score data[] = null;
public ScoreAdapter(Context context, int layoutResourceId, Score[] data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ScoreHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new ScoreHolder();
holder.txtScore = (TextView)row.findViewById(R.id.txtScore);
holder.txtScoreChange = (TextView)row.findViewById(R.id.txtScoreChange);
holder.txtName = (TextView)row.findViewById(R.id.txtName);
row.setTag(holder);
}
else
{
holder = (ScoreHolder)row.getTag();
}
Score scoreData = data[position];
holder.txtName.setText(scoreData.name);
holder.txtScore.setText(scoreData.score);
return row;
}
static class ScoreHolder
{
TextView txtScore;
TextView txtName;
TextView txtScoreChange;
}
}
Call adapter.notifyDataSetChanged(). That will cause it to repopulate the listview, calling adapter.getView on all visible views. Have getView() set the correct values for its row.