setCompoundDrawables button android not showing images - android

I want to create button with image in grid view below is my code:
My FragmentHome.java:
package com.erlanggastudio.myagri.fragments;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import com.erlanggastudio.myagri.R;
import com.erlanggastudio.myagri.adapters.AdapaterGridView;
import com.erlanggastudio.myagri.adapters.AdapterGridViewItem;
import com.erlanggastudio.myagri.adapters.AdapterImageSlider;
import java.util.ArrayList;
public class FragmentHome extends Fragment implements ViewPager.OnPageChangeListener {
//For Page Viewer Dots
//private ImageButton btnNext, btnFinish;
private ViewPager intro_images;
private LinearLayout pager_indicator;
private int dotsCount;
private ImageView[] dots;
private AdapterImageSlider mAdapter;
private int[] mImageResources = {
R.drawable.image_header_1,
R.drawable.image_header_2,
R.drawable.image_header_3
};
GridView gridview;
AdapaterGridView gridviewAdapter;
ArrayList<AdapterGridViewItem> data = new ArrayList<AdapterGridViewItem>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_home, container, false);
intro_images = (ViewPager) v.findViewById(R.id.viewPage1);
pager_indicator = (LinearLayout) v.findViewById(R.id.viewPagerCountDots);
mAdapter = new AdapterImageSlider(getActivity(), mImageResources);
intro_images.setAdapter(mAdapter);
intro_images.setCurrentItem(0);
intro_images.setOnPageChangeListener(this);
setUiPageViewController();
gridview = (GridView) v.findViewById(R.id.gridView1);
data.add(new AdapterGridViewItem(getResources().getString(R.string.menu_product), ContextCompat.getDrawable(getActivity(), R.drawable.ic_product),0));
data.add(new AdapterGridViewItem(getResources().getString(R.string.menu_cart), ContextCompat.getDrawable(getActivity(), R.drawable.ic_cart),1));
data.add(new AdapterGridViewItem(getResources().getString(R.string.menu_checkout), ContextCompat.getDrawable(getActivity(), R.drawable.ic_checkout),2));
data.add(new AdapterGridViewItem(getResources().getString(R.string.menu_info), ContextCompat.getDrawable(getActivity(), R.drawable.ic_info),3));
data.add(new AdapterGridViewItem(getResources().getString(R.string.menu_profile), ContextCompat.getDrawable(getActivity(), R.drawable.ic_profile),4));
data.add(new AdapterGridViewItem(getResources().getString(R.string.menu_about), ContextCompat.getDrawable(getActivity(), R.drawable.ic_about),5));
setDataAdapter();
return v;
}
// Set the Data Adapter
private void setDataAdapter() {
gridviewAdapter = new AdapaterGridView(getActivity(), R.layout.lsv_item_mainmenu, data);
gridview.setAdapter(gridviewAdapter);
}
private void setUiPageViewController() {
dotsCount = mAdapter.getCount();
dots = new ImageView[dotsCount];
for (int i = 0; i < dotsCount; i++) {
dots[i] = new ImageView(getActivity());
dots[i].setImageDrawable(getResources().getDrawable(R.drawable.nonselecteditem_dot));
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT
);
params.setMargins(4, 0, 4, 0);
pager_indicator.addView(dots[i], params);
}
dots[0].setImageDrawable(getResources().getDrawable(R.drawable.selecteditem_dot));
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
for (int i = 0; i < dotsCount; i++) {
dots[i].setImageDrawable(getResources().getDrawable(R.drawable.nonselecteditem_dot));
}
dots[position].setImageDrawable(getResources().getDrawable(R.drawable.selecteditem_dot));
}
#Override
public void onPageScrollStateChanged(int state) {
}
}
Adapter code is :
package com.erlanggastudio.myagri.adapters;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;
import com.erlanggastudio.myagri.R;
import com.erlanggastudio.myagri.activities.ActivityAbout;
import com.erlanggastudio.myagri.activities.ActivityCart;
import com.erlanggastudio.myagri.activities.ActivityCheckout;
import com.erlanggastudio.myagri.activities.ActivityInformation;
import com.erlanggastudio.myagri.activities.ActivityMenuCategory;
import com.erlanggastudio.myagri.activities.ActivityProfile;
import java.util.ArrayList;
public class AdapaterGridView extends ArrayAdapter<AdapterGridViewItem> {
Context mContext;
int resourceId;
ArrayList<AdapterGridViewItem> data = new ArrayList<AdapterGridViewItem>();
public AdapaterGridView(Context context, int layoutResourceId, ArrayList<AdapterGridViewItem> data) {
super(context, layoutResourceId, data);
this.mContext = context;
this.resourceId = layoutResourceId;
this.data = data;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View itemView = convertView;
ViewHolder holder = null;
if (itemView == null) {
final LayoutInflater layoutInflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
itemView = layoutInflater.inflate(resourceId, parent, false);
holder = new ViewHolder();
holder.btnItem = (Button) itemView.findViewById(R.id.buttonMenu);
holder.txtItem = (TextView) itemView.findViewById(R.id.name);
itemView.setTag(holder);
} else {
holder = (ViewHolder) itemView.getTag();
}
final AdapterGridViewItem item = getItem(position);
holder.btnItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (item.getPoss() == 0) {
mContext.startActivity(new Intent(mContext, ActivityMenuCategory.class));
} else if (item.getPoss() == 1) {
mContext.startActivity(new Intent(mContext, ActivityCart.class));
} else if (item.getPoss() == 2) {
mContext.startActivity(new Intent(mContext, ActivityCheckout.class));
} else if (item.getPoss() == 3) {
mContext.startActivity(new Intent(mContext, ActivityInformation.class));
} else if (item.getPoss() == 4) {
mContext.startActivity(new Intent(mContext, ActivityProfile.class));
} else {
mContext.startActivity(new Intent(mContext, ActivityAbout.class));
}
}
});
holder.btnItem.setCompoundDrawables(null, item.getImage(), null,null);
holder.txtItem.setText(item.getTitle());
return itemView;
}
static class ViewHolder {
Button btnItem;
TextView txtItem;
}
}
And layout code is :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="vertical"
android:paddingTop="10dp">
<Button
android:id="#+id/buttonMenu"
android:layout_width="100dp"
android:layout_height="100dp"
android:background="#drawable/button_bg"
android:paddingTop="20dp"/>
<TextView
android:id="#+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:gravity="center_horizontal"
android:textSize="16sp"
android:paddingTop="10dp"/>
</LinearLayout>
</RelativeLayout>
I'm try to show dinamicly image in button using :
holder.btnItem.setCompoundDrawables(null, item.getImage(), null,null);
But the image in button not showing, this is my result:
any wrong with my code or i'm miss shomething.....???

Try this,
holder.btnItem.setCompoundDrawablesWithIntrinsicBounds(0,item.getImage(),0,0);

Related

Unable to make my circular menu look like the image provided

I can't find a tutorial to help me create a menu in Wearable RecyclerView. Everything that pops up up is related to Recyclerview for mobile phones. So I'm asking does the Wearable version work in the same manner or not?
I followed what was in the documentation but I don't know how to add items so that I would end up with something like this:
Edit:
So after messing around a bit and seeing the code for the Recyclerview here:https://codinginflow.com/tutorials/android/simple-recyclerview-java/part-2-adapter (Very helpful by the way)
I managed to create a list of items. Problem is they're lined up vertically with large spaces between them. I have placed the lines of code in the documentation that were supposed to line them up like in the image but I don't know what the problem is.
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Adapter;
import android.widget.Button;
import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.wear.ambient.AmbientModeSupport;
import androidx.wear.widget.WearableLinearLayoutManager;
import androidx.wear.widget.WearableRecyclerView;
import java.util.ArrayList;
import java.util.List;
public class circular_menu_external extends FragmentActivity
implements AmbientModeSupport.AmbientCallbackProvider, MenuItem.OnMenuItemClickListener {
// Fragment toolsfragment = new Tools();
// Fragment modesfragment = new Modes();
// Fragment keysfragment = new Keys();
// Fragment flowratefragment = new Flowrates();
private WearableRecyclerView wearableRecyclerView;
private Button btn;
private ArrayList<ExampleItem> mExampleList;
private RecyclerView.Adapter mAdapter;
private WearableRecyclerView.LayoutManager mLayoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_circular_menu_external);
wearableRecyclerView = findViewById(R.id.main_recycler_view);
mAdapter = new MenuRecyclerViewAdapter(mExampleList);
//Create a curved layout
CustomScrollingLayoutCallback customScrollingLayoutCallback = new CustomScrollingLayoutCallback();
// WearableLinearLayoutManager wearableLinearLayoutManager = new WearableLinearLayoutManager(this);
// wearableRecyclerView.setLayoutManager(wearableLinearLayoutManager);
// CustomScrollingLayoutCallback customScrollingLayoutCallback = new CustomScrollingLayoutCallback();
wearableRecyclerView.setLayoutManager(
new WearableLinearLayoutManager(this, customScrollingLayoutCallback));
// wearableRecyclerView.setLayoutManager(new WearableLinearLayoutManager(this));
wearableRecyclerView.setEdgeItemsCenteringEnabled(true);
createExampleList();
buildRecyclerView();
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
}
private void action_1() {
Intent i1 = new Intent(circular_menu_external.this, Settings.class);
startActivity(i1);
}
private void action_2(){
Intent i1 = new Intent(circular_menu_external.this, tool1mode1.class);
startActivity(i1);
}
private void action_3(){
Intent i1 = new Intent(circular_menu_external.this, tool1mode2.class);
startActivity(i1);
}
private void action_4(){
Intent i1 = new Intent(circular_menu_external.this, tool1mode3.class);
startActivity(i1);
}
private void cancelMenu(){
Intent i1 = new Intent(circular_menu_external.this, Main_menu.class);
startActivity(i1);
}
#Override
public boolean onMenuItemClick(MenuItem item) {
return false;
}
#Override
public AmbientModeSupport.AmbientCallback getAmbientCallback() {
return null;
}
public void createExampleList() {
mExampleList = new ArrayList<>();
mExampleList.add(new ExampleItem(R.drawable.tool_ic, "Line 1", "Line 2"));
mExampleList.add(new ExampleItem(R.drawable.mode_ic, "Line 3", "Line 4"));
mExampleList.add(new ExampleItem(R.drawable.key, "Line 5", "Line 6"));
mExampleList.add(new ExampleItem(R.drawable.flow_ic, "Line 7", "Line 8"));
}
public void buildRecyclerView() {
wearableRecyclerView.setEdgeItemsCenteringEnabled(true);
wearableRecyclerView.setHasFixedSize(true);
wearableRecyclerView.setEdgeItemsCenteringEnabled(true);
mLayoutManager = new LinearLayoutManager(this);
mAdapter = new MenuRecyclerViewAdapter(mExampleList);
wearableRecyclerView.setLayoutManager(mLayoutManager);
wearableRecyclerView.setAdapter(mAdapter);
//Add a circular scrolling gesture
wearableRecyclerView.setCircularScrollingGestureEnabled(true);
wearableRecyclerView.setBezelFraction(0.5f);
wearableRecyclerView.setScrollDegreesPerScreen(90);
}
public class CustomScrollingLayoutCallback extends WearableLinearLayoutManager.LayoutCallback {
/** How much should we scale the icon at most. */
private static final float MAX_ICON_PROGRESS = 0.65f;
private float progressToCenter;
#Override
public void onLayoutFinished(View child, RecyclerView parent) {
// Figure out % progress from top to bottom
float centerOffset = ((float) child.getHeight() / 2.0f) / (float) parent.getHeight();
float yRelativeToCenterOffset = (child.getY() / parent.getHeight()) + centerOffset;
// Normalize for center
progressToCenter = Math.abs(0.5f - yRelativeToCenterOffset);
// Adjust to the maximum scale
progressToCenter = Math.min(progressToCenter, MAX_ICON_PROGRESS);
child.setScaleX(1 - progressToCenter);
child.setScaleY(1 - progressToCenter);
}
}
}
This is the adapter:
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.wear.widget.WearableRecyclerView;
import java.util.ArrayList;
public class MenuRecyclerViewAdapter extends WearableRecyclerView.Adapter<MenuRecyclerViewAdapter.ExampleViewHolder> {
private ArrayList<ExampleItem> mExampleList;
public static class ExampleViewHolder extends WearableRecyclerView.ViewHolder {
public ImageView mImageView1,mImageView2,mImageView3,mImageView4;
public ExampleViewHolder(View itemView) {
super(itemView);
mImageView1 = itemView.findViewById(R.id.imageView1);
mImageView2 = itemView.findViewById(R.id.imageView2);
mImageView3 = itemView.findViewById(R.id.imageView3);
mImageView4 = itemView.findViewById(R.id.imageView4);
}
}
public MenuRecyclerViewAdapter(ArrayList<ExampleItem> exampleList) {
mExampleList = exampleList;
}
#Override
public ExampleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.example_item, parent, false);
ExampleViewHolder evh = new ExampleViewHolder(v);
return evh;
}
#Override
public void onBindViewHolder(ExampleViewHolder holder, int position) {
ExampleItem currentItem = mExampleList.get(position);
holder.mImageView1.setImageResource(currentItem.getImageResource());
holder.mImageView2.setImageResource(currentItem.getImageResource());
holder.mImageView3.setImageResource(currentItem.getImageResource());
holder.mImageView4.setImageResource(currentItem.getImageResource());
}
#Override
public int getItemCount() {
return mExampleList.size();
}
}
the xml file for my items:
<?xml version="1.0" encoding="utf-8"?>
<androidx.wear.widget.CircularProgressLayout
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">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="4dp">
<ImageButton
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/round_shape"
android:src="#drawable/homeicon4"
tools:ignore="MissingConstraints" />
<ImageButton
android:id="#+id/imageView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/round_shape"
android:src="#drawable/bypass3"
tools:ignore="MissingConstraints" />
<ImageButton
android:id="#+id/imageView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/round_shape"
android:src="#drawable/dualflow3"
tools:ignore="MissingConstraints" />
<ImageButton
android:id="#+id/imageView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/round_shape"
android:src="#drawable/isolation3"
tools:ignore="MissingConstraints" />
</RelativeLayout>
</androidx.wear.widget.CircularProgressLayout>

How to add custom list into listview control?

I have a problem binding a listview with ArrayList. When the first Vegetable Category is clicked it should bring different 3 elements in the listview but only the first one is displayed on the listview the others didn't show up.
here is my code (I am new to android stuff)!!!!!!
it should bring the list like this
enter image description here
problem_list.xml
<?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="wrap_content">
<ImageView
android:id="#+id/problem_imageView"
android:layout_width="70dp"
android:layout_height="70dp"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="13dp"
android:layout_marginTop="13dp" />
<!--app:srcCompat="#drawable/pest" />-->
<TextView
android:id="#+id/englishName_textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/problem_imageView"
android:layout_marginStart="13dp"
android:layout_toEndOf="#+id/problem_imageView"
android:fontFamily="monospace"
android:text="Category English Name"
android:textAppearance="#style/TextAppearance.AppCompat.Medium" />
<TextView
android:id="#+id/amharicName_textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignStart="#+id/englishName_textView"
android:layout_below="#+id/englishName_textView"
android:layout_marginTop="4dp"
android:fontFamily="monospace"
android:text="Amharic Name"
android:textColor="#000080"
android:textSize="15sp" />
<TextView
android:id="#+id/count_textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignEnd="#+id/amharicName_textView"
android:layout_below="#+id/amharicName_textView"
android:layout_marginTop="8dp"
android:fontFamily="monospace"
android:text="Count"
android:textColor="#000080"
android:textSize="14sp" />
</RelativeLayout>
ProblemAdapter.java
package com.packageName;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
public class ProblemAdapter extends BaseAdapter {
private Context context;
private ArrayList<Integer> listID;
private ArrayList<String> English_Title;
private ArrayList<String> Amharic_Title;
private ArrayList<Integer> count;
public ProblemAdapter(Context context, ArrayList<Integer> listID,
ArrayList<String> name,ArrayList<String> Amharic_Title,ArrayList<Integer>
count) {
this.context = context;
this.listID = listID;
this.English_Title = name;
this.Amharic_Title= Amharic_Title;
this.count = count;
}
#Override
public int getCount() {
return English_Title.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = View.inflate(context, R.layout.problem_list, null);
} else {
ImageView img = convertView.findViewById(R.id.problem_imageView);
TextView txtView_Eng =
convertView.findViewById(R.id.englishName_textView);
//TextView txtView_Amc =
convertView.findViewById(R.id.amharicName_textView);
TextView txtView_Count =
convertView.findViewById(R.id.count_textView);
img.setImageResource(listID.get(position));
txtView_Eng.setText(English_Title.get(position));
txtView_Amc.setText(Amharic_Title.get(position));
txtView_Count.setText(count.get(position));
}
return convertView;
}
}
problem_category.java
package com.packageName;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import java.util.ArrayList;
public class problem_category extends AppCompatActivity {
String VegetableCategoryType ;
ListView listView;
ArrayList<Integer> ImageID;
ArrayList<String> English_Title;
ArrayList<String> Amharic_Title;
ArrayList<Integer> count;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_problem_category);
// Assigning caller plant to the VegetableCategoryType
Intent intent = getIntent();
VegetableCategoryType = intent.getStringExtra("Plant_Name");
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton)
findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Will be replaced with new action",
Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
listView = findViewById(R.id.category_List_view);
ImageID = new ArrayList<>();
English_Title = new ArrayList<>();
Amharic_Title = new ArrayList<>();
count = new ArrayList<>();
ImageID = getImageID();
English_Title = getEnglishName();
Amharic_Title = getAmharicName();
count = getCount();
ProblemAdapter pAdapter = new ProblemAdapter(problem_category.this,
ImageID,English_Title,Amharic_Title,count);
listView.setAdapter(pAdapter);
}
#Override
public void finish(){
super.finish();
overridePendingTransition(R.anim.slide_in_left,R.anim.slide_out_right);
}
public ArrayList<String> getEnglishName(){
English_Title= new ArrayList<>();
English_Title.add("Pest");
English_Title.add("Disease");
English_Title.add("Disorder");
return English_Title;
}
private ArrayList<String> getAmharicName() {
Amharic_Title= new ArrayList<>();
Amharic_Title.add("sub-title1");
Amharic_Title.add("sub-title2");
Amharic_Title.add("sub-title3");
return Amharic_Title;
}
public ArrayList<Integer> getImageID(){
ImageID = new ArrayList<>();
ImageID.add(R.drawable.pest);
ImageID.add(R.drawable.disease);
ImageID.add(R.drawable.disorder_edited);
return ImageID;
}
public ArrayList<Integer> getCount(){
count = new ArrayList<>();
if(VegetableCategoryType == "Cabbage"){
count.add(3);
count.add(8);
count.add(3);
}else if (VegetableCategoryType =="Pepper"){
count.add(7);
count.add(5);
count.add(2);
}else if(VegetableCategoryType == "Onion"){
count.add(2);
count.add(5);
count.add(3);
}else if(VegetableCategoryType == "Tomato"){
count.add(8);
count.add(16);
count.add(5);
}
return count;
}
}
MainActivity click_Listners()
public void click_Listeners(){
cabbageImageView.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
Intent pCategory = new
Intent(getApplicationContext(),problem_category.class);
pCategory.putExtra("Plant_Name","Cabbage");
startActivity(pCategory);
overridePendingTransition(R.anim.slide_in_right,R.anim.slide_out_left);
}
});
}
You are not setting the values for the new views created. Your getView body should look like this:
if (convertView == null) {
convertView = View.inflate(context, R.layout.problem_list, null);
} else {
ImageView img = convertView.findViewById(R.id.problem_imageView);
TextView txtView_Eng =
convertView.findViewById(R.id.englishName_textView);
//TextView txtView_Amc =
convertView.findViewById(R.id.amharicName_textView);
TextView txtView_Count =
convertView.findViewById(R.id.count_textView);
img.setImageResource(listID.get(position));
txtView_Eng.setText(English_Title.get(position));
txtView_Amc.setText(Amharic_Title.get(position));
txtView_Count.setText(count.get(position));
}
return convertView;

ListView item open a new fragment

I am making a fitness app, where I want to have 3 nesting :
ListView with muscle group items
ListView of exercises (appears when to click on item from the muscle group ListView)
and description of exercise.
Something like this design:
But I don't know how do realize this.
Do I need create a new fragment to each item or I can use ViewPager here(if yes,how to do this)?
Give me advice,please, how to realize this design (any links of the same structure projects or any other examples)
thank you in advance
Here is the sample code
package com.sw.gitans201608042027;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
public class MainActivity extends FragmentActivity {
private static MainActivity mCurrent = null;
public static MainActivity getInstance() {
return mCurrent;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mCurrent = this;
setContentView(R.layout.activity_main);
switchFragment(new ListFragment());
}
public void switchFragment(Fragment f) {
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction transaction = fm.beginTransaction();
transaction.replace(R.id.container, f);
transaction.commit();
}
}
package com.sw.gitans201608042027;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
public class ListFragment extends Fragment implements OnItemClickListener {
private String[] contents = { "a", "b" };
private String[] aArr = { "a1", "a2" }, bArr = { "b1", "b2" };
private SampleAdapter mAdapter;
public ListFragment(String[] contents) {
this.contents = contents;
}
public ListFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.lv, container, false);
mAdapter = new SampleAdapter(getActivity(), contents);
((ListView) v.findViewById(R.id.lv)).setAdapter(mAdapter);
((ListView) v.findViewById(R.id.lv)).setOnItemClickListener(this);
return v;
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
if (mAdapter.getItem(arg2) != null) {
if (((String) mAdapter.getItem(arg2)).equals("a") || ((String) mAdapter.getItem(arg2)).equals("b")) {
if (((String) mAdapter.getItem(arg2)).equals("a")) {
if (MainActivity.getInstance() != null)
MainActivity.getInstance().switchFragment(new ListFragment(aArr));
} else {
if (MainActivity.getInstance() != null)
MainActivity.getInstance().switchFragment(new ListFragment(bArr));
}
} else {
if (MainActivity.getInstance() != null)
MainActivity.getInstance().switchFragment(new TextFragment((String) mAdapter.getItem(arg2)));
}
}
}
}
package com.sw.gitans201608042027;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class SampleAdapter extends BaseAdapter {
private String[] contents;
private LayoutInflater mInflater;
public SampleAdapter(Context ctxt, String[] contents) {
this.contents = contents;
mInflater = LayoutInflater.from(ctxt);
}
#Override
public int getCount() {
if (contents != null)
return contents.length;
else
return 0;
}
#Override
public Object getItem(int position) {
if (contents == null || position >= contents.length)
return null;
else
return contents[position];
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Holder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item, null);
holder = new Holder();
holder.tv = (TextView) convertView.findViewById(R.id.list_txt);
convertView.setTag(holder);
} else
holder = (Holder) convertView.getTag();
holder.tv.setText(contents[position]);
return convertView;
}
private class Holder {
TextView tv;
}
}
package com.sw.gitans201608042027;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class TextFragment extends Fragment {
private String desc;
public TextFragment(String s){
desc = s;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.list_item, container, false);
((TextView)v.findViewById(R.id.list_txt)).setText(desc);
return v;
}
}
activity_main.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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.sw.gitans201608042027.MainActivity" >
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
list_item.xml
<?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" >
<TextView
android:id="#+id/list_txt"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</RelativeLayout>
lv.xml
<?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" >
<ListView
android:id="#+id/lv"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>

Android: ListView not working properly after scroll

Hi I'm trying to show text, image alternatively in list view. To load the content into my list view i had three scenarios.
1. Some times i'm getting only the text from json. So, in this case i have to hide the ImageView
2. Some cases i'm getting only the image url from json. So, in this case i have to hide the TextView
3. In other case i'm getting both image url and text from json, so, in this case i don't have to hide anything
By following these scenarios i'm loading all the content correctly at first time but when i'm scrolling top to bottom and bottom to up. All the image views are filled with images (But there is no image url for that particular position)
My adapter code is
package com.app.listviewitemid.adapter;
import java.util.ArrayList;
import com.app.listviewitemid.R;
import com.app.listviewitemid.model.Items;
import com.bumptech.glide.Glide;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class ItemsAdapter extends ArrayAdapter<Items>{
ArrayList<Items> itemsArrayList;
int Resource;
LayoutInflater inflater;
Context context;
ViewHolder holder;
Button btnCheck;
Items globPosition;
public ItemsAdapter(Context context, int resource, ArrayList<Items> objects){
super(context, resource, objects);
this.context = context;
this.Resource = resource;
this.itemsArrayList = objects;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if(v == null){
v = inflater.inflate(Resource, null);
holder = new ViewHolder();
holder.tvPostID = (TextView) v.findViewById(R.id.tv_post_id);
holder.tvPostText = (TextView) v.findViewById(R.id.tv_post_text);
holder.ivPostImage = (ImageView) v.findViewById(R.id.iv_post_img);
btnCheck = (Button) v.findViewById(R.id.btn_check);
v.setTag(holder);
}else{
holder = (ViewHolder) v.getTag();
}
globPosition = itemsArrayList.get(position);
holder.tvPostID.setText(itemsArrayList.get(position).getPostID());
if(globPosition.getPostText().equals(null) || globPosition.getPostText().equals("")){
}else {
holder.tvPostText.setText(globPosition.getPostText());
}
if(globPosition.getPostImage().equals(null) || globPosition.getPostImage().equals("")){
}else {
Glide.with(context).load(globPosition.getPostImage()).placeholder(R.drawable.loading_img).error(R.drawable.bg_480_800).into(holder.ivPostImage);
}
btnCheck.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Log.e("PostID", globPosition.getPostID());
}
});
return v;
}
static class ViewHolder{
TextView tvPostID;
TextView tvPostText;
ImageView ivPostImage;
}
}
adapter layout
<?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" >
<TextView
android:id="#+id/tv_post_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/post_id"
android:textColor="#000000"
android:textSize="12sp" />
<TextView
android:id="#+id/tv_post_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000000"
android:textSize="12sp" />
<ImageView
android:id="#+id/iv_post_img"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="#string/empty" />
<Button
android:id="#+id/btn_check"
android:layout_width="match_parent"
android:layout_height="35dp"
android:background="#000000"
android:text="#string/check"
android:textColor="#FFFFFF" />
</LinearLayout>
How to get rid of this?
if(globPosition.getPostText().equals(null) || globPosition.getPostText().equals("")){
holder.tvPostText.setVisibility(View.GONE);
}else {
holder.ivPostImage.setVisibility(View.GONE);
holder.tvPostText.setVisibility(View.VISIBLE);
holder.tvPostText.setText(globPosition.getPostText());
}
if(globPosition.getPostImage().equals(null) || globPosition.getPostImage().equals("")){
holder.ivPostImage.setVisibility(View.GONE);
}else {
holder.ivPostImage.setVisibility(View.GONE);
holder.tvPostText.setVisibility(View.VISIBLE);
Glide.with(context).load(globPosition.getPostImage()).placeholder(R.drawable.loading_img).error(R.drawable.bg_480_800).into(holder.ivPostImage);
}
I got the idea from ankit aggarwal answer (his code is not working properly but he gave me the basic idea). And one more thing, previously i didn't get the correct position, so i changed the adapter code little bit
Code
package com.app.listviewitemid.adapter;
import java.util.List;
import com.app.listviewitemid.R;
import com.app.listviewitemid.model.Items;
import com.bumptech.glide.Glide;
import android.annotation.SuppressLint;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class ItemsAdapter extends BaseAdapter{
List<Items> itemsArrayList;
int Resource;
LayoutInflater inflater;
Context context;
Button btnCheck;
public ItemsAdapter(Context context, List<Items> items) {
this.context = context;
this.itemsArrayList = items;
}
#Override
public int getCount() {
return itemsArrayList.size();
}
#Override
public Object getItem(int location) {
return itemsArrayList.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#SuppressLint("InflateParams") #Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.adapter_layout, null);
TextView tvPostID = (TextView) convertView.findViewById(R.id.tv_post_id);
TextView tvPostText = (TextView) convertView.findViewById(R.id.tv_post_text);
ImageView ivPostImage = (ImageView) convertView.findViewById(R.id.iv_post_img);
btnCheck = (Button) convertView.findViewById(R.id.btn_check);
final Items items = itemsArrayList.get(position);
tvPostID.setText(items.getPostID());
if(items.getPostText().equals(null) || items.getPostText().equals("")){
tvPostText.setVisibility(View.GONE);
}else {
//ivPostImage.setVisibility(View.GONE);
if(items.getPostImage().equals(null) || items.getPostImage().equals("")){
ivPostImage.setVisibility(View.GONE);
}else {
ivPostImage.setVisibility(View.VISIBLE);
tvPostText.setVisibility(View.GONE);
Glide.with(context).load(items.getPostImage()).placeholder(R.drawable.loading_img).error(R.drawable.bg_480_800).into(ivPostImage);
}
tvPostText.setVisibility(View.VISIBLE);
tvPostText.setText(items.getPostText());
}
if(items.getPostImage().equals(null) || items.getPostImage().equals("")){
ivPostImage.setVisibility(View.GONE);
}else {
ivPostImage.setVisibility(View.VISIBLE);
//tvPostText.setVisibility(View.GONE);
if(items.getPostText().equals(null) || items.getPostText().equals("")){
tvPostText.setVisibility(View.GONE);
}else {
tvPostText.setVisibility(View.VISIBLE);
tvPostText.setText(items.getPostText());
}
Glide.with(context).load(items.getPostImage()).placeholder(R.drawable.loading_img).error(R.drawable.bg_480_800).into(ivPostImage);
}
btnCheck.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Log.e("PostID", items.getPostID());
}
});
return convertView;
}
}
Thanks to ankit aggarwal

Custom ListView not showing any items

I am trying to display a custom listview but nothing appears.
My activity:
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import com.example.elnoorgeh.ServerAPI;
import android.app.Fragment;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView.FindListener;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
public class BlogFragment extends Fragment {
JSONArray jArray;
TextView title;
RelativeLayout layout;
int previousID = 0;
int currentID = 0;
ArrayList<String> titles;
ArrayList<String> contents;
ListView list;
public BlogFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_blog, container,
false);
new AsyncFetch().execute();
return rootView;
}
private class AsyncFetch extends AsyncTask<Object, Object, Object> {
#Override
protected Object doInBackground(Object... params) {
// TODO Auto-generated method stub
jArray = new JSONArray();
jArray = ServerAPI.getData();
titles = new ArrayList<String>();
contents = new ArrayList<String>();
for (int i = 0; i < jArray.length(); i++) {
String blogTitle = null;
String content = null;
try {
blogTitle = jArray.getJSONObject(i).getString("title");
content = jArray.getJSONObject(i).getString("content");
titles.add(blogTitle);
contents.add(content);
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println(blogTitle);
System.out.println(content);
}
// display(titles, contents);
return null;
}
protected void onPostExecute(Object result) {
layout = (RelativeLayout) getView().findViewById(R.id.blogPage);
layout.removeAllViews();
CustomList adapter = new CustomList(getActivity(), titles);
list = new ListView(getActivity());
System.out.println("list done");
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getActivity(),
"You Clicked at " + titles.get(position),
Toast.LENGTH_SHORT).show();
}
});
}
}
public void display(ArrayList<String> t, ArrayList<String> c) {
}
}
Custom ListView class:
import java.util.ArrayList;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class CustomList extends ArrayAdapter<String> {
private final Activity context;
private final ArrayList<String> web;
// private final Integer[] imageId;
public CustomList(Activity context, ArrayList<String>web) {
super(context, R.layout.fragment_listview);
this.context = context;
this.web = web;
// this.imageId = imageId;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView = inflater.inflate(R.layout.fragment_listview, null, true);
TextView txtTitle = (TextView) rowView.findViewById(R.id.txt);
ImageView imageView = (ImageView) rowView.findViewById(R.id.img);
txtTitle.setText((CharSequence) web.get(position));
// imageView.setImageResource(imageId[position]);
return rowView;
}
}
fragment_blog:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/blogPage"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</ListView>
<TextView
android:id="#+id/txtLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:maxLines="20"
android:singleLine="false"
android:textSize="16dp" />
</RelativeLayout>
fragment_listview:
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TableRow>
<ImageView
android:id="#+id/img"
android:layout_width="50dp"
android:layout_height="50dp" />
<TextView
android:id="#+id/txt"
android:layout_width="wrap_content"
android:layout_height="50dp" />
</TableRow>
</TableLayout>
I can't find any errors or notice something irregular, so why is that happening?
you should extend BaseAdapter and implement abstract methods
#Override
public int getCount() {
return web.size();
}
#Override
public Object getItem(int position) {
return web.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
also you might change
txtTitle.setText((CharSequence) web.get(position));
to
txtTitle.setText((CharSequence) getItem(position));
now your adapter don't know size of web array
edit:
you can get one inflater in constructor and keep in class, no need to getting inflater each time (little bit better for perfomance)
LayoutInflater inflater = context.getLayoutInflater();
edit 2:
localhost put proper comment - you are removing all Views from RelativeLayout, also ListView, and creating new ListView without adding to Relative. keeping reference will not auto-add View
protected void onPostExecute(Object result) {
layout = (RelativeLayout) getView().findViewById(R.id.blogPage);
layout.removeView(getView().findViewById(R.id.txtLabel);
//assuming you need to remove only txtLabel
CustomList adapter = new CustomList(getActivity(), titles);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getActivity(),
"You Clicked at " + titles.get(position),
Toast.LENGTH_SHORT).show();
}
});
}

Categories

Resources