How can I add my Dynamic Layout to ListView? - android

I have created a Dynamic LinearLayout and I want to add these layouts to ListView. The code is as follows:
DynamicLayout code:
import android.content.Context;
import android.widget.LinearLayout;
import android.widget.TextView;
public class DynamicContentLayout extends LinearLayout{
private Context context;
private int linearLayoutMargin;
public DynamicContentLayout(Context context) {
super(context);
this.context = context;
linearLayoutMargin = (int) context.getResources().getDimension(R.dimen.xlarge_margin_padding_fixed);
initViews();
}
private void initViews() {
LinearLayout.LayoutParams layout_lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
layout_lp.setMargins(linearLayoutMargin, linearLayoutMargin, linearLayoutMargin, linearLayoutMargin);
this.setLayoutParams(layout_lp);
this.setOrientation(LinearLayout.VERTICAL);
this.addView(headerTitle("My Text"));
}
private TextView headerTitle(String title) {
TextView txtView = new TextView(context);
txtView.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
txtView.setPadding(6, 6, 6, 6);
txtView.setText(title);
txtView.setBackgroundColor(context.getResources().getColor(R.color.red));
txtView.setTextColor(context.getResources().getColor(R.color.white));
return txtView;
}
}
ListAdpaterCode:
import java.util.ArrayList;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
public class ListViewAdapter extends ArrayAdapter<DynamicContentLayout> {
private Context context;
private ArrayList<DynamicContentLayout> layoutList = null;
public ListViewAdapter(Context context, int textViewResourceId, ArrayList<DynamicContentLayout> layoutList) {
super(context, textViewResourceId, layoutList);
this.context = context;
this.layoutList = layoutList;
}
#Override
public int getCount() {
return layoutList.size();
}
#Override
public DynamicContentLayout getItem(int position){
return layoutList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
DynamicContentLayout entry = (DynamicContentLayout) layoutList.get(position);
convertView = (View) entry;
return convertView;
}
}
Finally the code in the MainActivity where I am setting the Adapter:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView = (ListView) findViewById(R.id.listView);
ArrayList<DynamicContentLayout> contents = new ArrayList<DynamicContentLayout>();
contents.add(new DynamicContentLayout(getApplicationContext()));
contents.add(new DynamicContentLayout(getApplicationContext()));
contents.add(new DynamicContentLayout(getApplicationContext()));
ArrayAdapter<DynamicContentLayout> arrayAdapter = new ArrayAdapter<DynamicContentLayout>(getApplicationContext(), android.R.layout.simple_list_item_1, contents);
listView.setAdapter(arrayAdapter);
arrayAdapter.notifyDataSetChanged();
}
Xml Layout:
<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"
>
<ListView
android:id="#+id/listView"
android:layout_width="fill_parent"
android:background="#color/blue"
android:layout_height="fill_parent"
android:alwaysDrawnWithCache="true"
android:clickable="true"
android:layout_alignParentTop="true"
android:divider="#color/grey"
android:drawingCacheQuality="auto"
android:fastScrollEnabled="true"
android:paddingLeft="15dp"
android:paddingRight="15dp"
android:scrollbars="none" >
</ListView>
</RelativeLayout>
Now, when I run , there is no error reported. But I couldn't see listItems layouts. What I can see is name of the class only. for example: "com.myexample.dynamicontentoverview.DynamicContentLayout#405193d0" as the row of the listItem instead of the Layout.
There is one more point I want to add. I cannot use XMl Layout as my views inside my DynamicLinearLayout can increase/decrease for certain rows.
Please suggests something.
Thanks.

You got the concept of custom listViews all wrong.
You should define your custom layout in an xml layout.
The type of your array adapter shouldn't be a layout. It should be the object type you are trying to populate the listView with.
Check out this tutorial to get a better idea of the steps you should do.

You are using ArrayAdapter as your adapter for the ListView instead of your own ListViewAdapter which extends ArrayAdapter< DynamicContentLayout>
What you are seeing now is your objects toString representation, because, well, thats what the ArrayAdapter does.

Related

A ListView containing only images

how can i make a listView that only contains images and nothing else. i am new to the listView and all that adapter stuff. i succeed in making a listView containing text only but unable to do this with images.
this is what i have done so far.
My MainActivity Class
public class MainActivity extends AppCompatActivity {
ListView listView;
ImageView imageView;
int[] imageIds = {R.drawable.chrysanthemum, R.drawable.desert, R.drawable.hydrangeas, R.drawable.jellyfish};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView);
ArrayAdapter<ImageView> adapter = new ArrayAdapter<ImageView>(this, R.layout.imageview, imageIds);
listView.setAdapter(adapter);
}
}
Main XML code
<RelativeLayout 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="com.example.danishrizvi.myapplication.MainActivity">
<ListView
android:id="#+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
ImageView Layout File
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
the error arises in this line ArrayAdapter<ImageView> adapter = new ArrayAdapter<ImageView>(this, R.layout.imageview, imageIds); that is Unable to Resolve Constructor.
so far what i have learned about my mistake by searching on the internet is that i might need a custom adapter or something similar to get my job done but was unable to know that how to implement and how that works.
layout_adapter.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<ImageView
android:id="#+id/img_adapter"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
ImageAdapter.java
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import java.util.ArrayList;
public class ImageAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<String> arrayList;
public ImageAdapter(Context mContext, ArrayList<String> arrayList) {
this.mContext = mContext;
this.arrayList = arrayList;
}
#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) {
convertView = LayoutInflater.from(mContext).inflate(R.layout.layout_adapter, parent, false);
ImageView imgAdapter = (ImageView) convertView.findViewById(R.id.img_adapter);
Glide.with(mContext).load(arrayList.get(position)).into(imgAdapter);
return convertView;
}
}
Use this in activity like this,
ArrayList<String> arrayList = new ArrayList<>();
arrayList.add("image url");
arrayList.add("image url");
arrayList.add("image url");
ImageAdapter imageAdapter = new ImageAdapter(this, arrayList);
listView.setAdapter(imageAdapter);
sample code is here:
https://www.androidhive.info/2012/02/android-custom-listview-with-image-and-text/
Ii is showing row with image and text. So you can modified it according to your requirement.

How to create a listview with 2 columns showing all installed android apps and the permissions along with it?

I'm pretty newbie to Android development (2 days old).
I intend to create an app that list all the currently installed applications in the device and a column beside each of those results showing the permissions granted. I understand that conventionally a listView has 1 column , how do I make another column ?
I'm open to other ideas as well (like perhaps another intent when i click the installed application name ?)
Below is my code thus far which shows all installed applications :
import android.app.Activity;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextSwitcher;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class PopAnalysis extends Activity{
ListView appList;
private TextSwitcher mSwitcher;
TextView myText;
private ArrayList results = new ArrayList();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.popupanalysis);
appList = (ListView)findViewById(R.id.listViewApp);
PackageManager pm = this.getPackageManager();
Intent intent = new Intent(Intent.ACTION_MAIN,null);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
ArrayList<ResolveInfo> list = (ArrayList<ResolveInfo>) pm.queryIntentActivities(intent, PackageManager.PERMISSION_GRANTED);
for (ResolveInfo rInfo : list) {
results.add(rInfo.activityInfo.applicationInfo.loadLabel(pm).toString());
System.out.println(rInfo.activityInfo.applicationInfo.loadLabel(pm).toString());
}
appList.setAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1, results));
appList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int itemposition = position;
String value = (String) appList.getItemAtPosition(position);
}
});
}
}
Following are my XML codes :
<?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:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listViewApp"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="56dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/textViewAnalysis"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:id="#+id/list_item_appname"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="2"
android:textAppearance="#android:style/TextAppearance.Medium" />
<TextView
android:id="#+id/list_item_apppermissions"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1" />
</RelativeLayout>
Firstly you need load apps list and permission for every apps. I do it inside Activity.onCreate to simplify example. The better way to do it inside AsyncTask
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final PackageManager packageManager = getPackageManager();
final List<Pair<String, List<String>>> appsWithPermission = new ArrayList<>();
final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
final List<ResolveInfo> apps = packageManager.queryIntentActivities(mainIntent, 0);
for (ResolveInfo info : apps) {
final ApplicationInfo applicationInfo = info.activityInfo.applicationInfo;
final String appName = (String) applicationInfo.loadLabel(packageManager);
final List<String> permissions = new ArrayList<>();
if (appName != null) {
try {
final PackageInfo packageInfo = packageManager.getPackageInfo(applicationInfo.packageName, PackageManager.GET_PERMISSIONS);
final String[] requestedPermissions = packageInfo.requestedPermissions;
if (requestedPermissions != null) {
permissions.addAll(Arrays.asList(requestedPermissions));
}
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
}
appsWithPermission.add(new Pair<>(appName, permissions));
}
final ListView listView = (ListView) findViewById(R.id.list_view);
final AppsAdapter appsAdapter = new AppsAdapter(this, appsWithPermission);
listView.setAdapter(appsAdapter);
}
}
Secondly you need xml layout list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/list_item_appname"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="2"
android:textAppearance="#android:style/TextAppearance.Medium" />
<TextView
android:id="#+id/list_item_apppermissions"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1" />
</LinearLayout>
and finally AppsAdapter.java
public class AppsAdapter extends BaseAdapter {
private final Context mContext;
private List<Pair<String, List<String>>> mAppsWithPermission;
public AppsAdapter(Context context, List<Pair<String, List<String>>> appsWithPermission) {
mContext = context;
mAppsWithPermission = appsWithPermission;
}
static class ViewHolder {
public TextView appName;
public TextView appPermissions;
}
#Override
public int getCount() {
return mAppsWithPermission.size();
}
#Override
public Object getItem(int position) {
return mAppsWithPermission.get(position);
}
#Override
public long getItemId(int position) {
return mAppsWithPermission.get(position).hashCode();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = LayoutInflater.from(mContext).inflate(R.layout.list_item, parent, false);
holder = new ViewHolder();
holder.appName = (TextView) convertView.findViewById(R.id.list_item_appname);
holder.appPermissions = (TextView) convertView.findViewById(R.id.list_item_apppermissions);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Pair<String, List<String>> item = mAppsWithPermission.get(position);
holder.appName.setText(item.first);
holder.appPermissions.setText(item.second.toString());
return convertView;
}
}
I see you've already figured out how to get a list of all installed applications and their respective permissions, which is good. In order to make a ListView with multiple columns, though, you'll need to implement a ListViewAdapter.
A really great resource for figuring out how to do this can be found here.
If you're confused about anything on that link, or something doesn't work, let me know.
Code:
PopAnalysis.java
public class PopAnalysis extends Activity {
public static final String FIRST_COLUMN = "First";
public static final String SECOND_COLUMN = "Second";
ListView appList;
private TextSwitcher mSwitcher;
TextView myText;
private ArrayList results = new ArrayList();
private ArrayList<HashMap<String, String>> list;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.popupanalysis);
appList = (ListView)findViewById(R.id.listViewApp);
HashMap<String,String> t1 = new HashMap<String, String>();
t1.put(FIRST_COLUMN, "App 1");
t1.put(SECOND_COLUMN, "Permission 1");
list.add(t1);
ListViewAdapter adapter = new ListViewAdapter(this, list);
listView.setAdapter(adapter);
}
}
ListViewAdapter.java
public class ListViewAdapter extends BaseAdapter {
public static final String FIRST_COLUMN = "First";
public static final String SECOND_COLUMN = "Second";
public ArrayList<HashMap<String, String>> list;
Activity activity;
TextView txtFirst;
TextView txtSecond;
public ListViewAdapter(Activity activity,ArrayList<HashMap<String, String>> list){
super();
this.activity=activity;
this.list=list;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater=activity.getLayoutInflater();
if(convertView == null){
convertView=inflater.inflate(R.layout.column_row_layout, null);
txtFirst=(TextView) convertView.findViewById(R.id.application);
txtSecond=(TextView) convertView.findViewById(R.id.permissions);
}
HashMap<String, String> map=list.get(position);
txtFirst.setText(map.get(FIRST_COLUMN));
txtSecond.setText(map.get(SECOND_COLUMN));
return convertView;
}
}
column_row_layout.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<TextView android:id="#+id/application"
android:layout_height="wrap_content"
android:layout_width="0dp"
android:layout_weight="1"
android:textStyle="bold" />
<TextView android:id="#+id/permissions"
android:layout_height="wrap_content"
android:layout_width="0dp"
android:layout_weight="1"/>
</LinearLayout>
In PopAnalysis.java I added only one entry to simply show how it's done. Certainly you shouldn't have any issues implementing the data you want into it.
Instead of 2 column listview , you can also try ExpandableListView. Clicking on the item with expand a detail view just below to it.
detail view will contain the permissions of that app.
Expandable Listview Tutorial
BTW, there is no way in SDK's listview to have multiple column. What you can do is to have a pseudo-multicolumn list view like using multiple textview(or other kind of view) in the same row. In that case you will need to make a custom adapter for your list view and a custom row layout file.
If you really want to have something multi-column, then either 3rd party libraries or TableLayout is your only option.
TableLayout tutorial
to make two column listview you have to implement custom listview. please read this link
in program_list.xml instead of imageview take textview it will resolve your problem.

Android ListView displays nothing but doesn't crash

I followed all the steps from various sources for getting listviews to work but my one
doesn't seem to display anything. This list view code(shown below) is activated with a tab fragment manager I won't put that here as to not bog you all down with code as there's a lot here already. It is most likely a problem with the ListFragment itself but I suppose it could be the adapter.
What happens is nothing gets displayed at all just the searchview that I have put in the main xml layout. I can switch freely between tabs with no crashes but just nothing displays in any of my listviews. I have another list which is a friends list(not included in this code snippet) and that uses a generic view holder interface and that one does not work either which suggests the problem is most likely in my ListFragment but I just can't pinpoint it. Any help is appreciated and I hope some can learn something from this, Thank you.
This is my adapter for the settings category list
package codeblox.com.listfragmentexample;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.ToggleButton;
import java.util.ArrayList;
import codblox.com.listfragmentexample.R;
public class SettingsAdapter extends ArrayAdapter<Settings.SettingsCategories>
{
private final Activity context;
String[] text;
ArrayList<Settings.SettingsCategories> itemsCopy;
class ViewHolder
{
public TextView txt;
public CheckBox state;
public ImageView settingImg;
public EditText input;
public ToggleButton toggle;
public Button settingInfo; // click it to show what the setting does
}
public SettingsAdapter(Context context, ArrayList<Settings.SettingsCategories> items)
{
super(context, R.layout.settings_category_row, items);
this.context = (Activity) context;
this.itemsCopy = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
ViewHolder holder = new ViewHolder();
int viewType = this.getItemViewType(position);
if(convertView == null)
{
// inflate the GridView item layout
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.settings_category_row, parent, false);
// initialize the view holder
holder = new ViewHolder();
holder.settingImg = (ImageView) convertView.findViewById(R.id.settingCategoryImg);
holder.txt = (TextView) convertView.findViewById(R.id.settingCategoryName);
convertView.setTag(holder);
} else {
// recycle the already inflated view
holder = (ViewHolder) convertView.getTag();
}
// fill data
holder = (ViewHolder) convertView.getTag();
String s = getItem(position).toString();
holder.txt.setText(itemsCopy.get(position).getSettingText());
holder.settingImg.setImageResource(itemsCopy.get(position).getImgResId());
return convertView;
}
}
This is my list fragment
package codeblox.com.listfragmentexample
import android.content.res.Resources;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
import codeblox.com.listfragmentexample.R;
public class Settings extends ListFragment implements View.OnLongClickListener
{
private ListView settingsList;
private ArrayList<SettingsCategories> mItems;
private ArrayAdapter<SettingsCategories> settingsAdapter;
private int numCategories;
String[] CategoryArray = new String[] {"Privacy and Security","Account","Networks","Camera Options","Storage","Accesibility","Features"};
int[] resIds = new int[] {R.drawable.security_settings_icon,R.drawable.account_settings_icon,
R.drawable.network_settings_icon,R.drawable.camera_settings_icon,R.drawable.storage_settings_icon,
R.drawable.accessibility_settings_icon,R.drawable.feature_settings_icon,};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View settingsView = inflater.inflate(R.layout.settings, container, false);
settingsList = (ListView)settingsView.findViewById(android.R.id.list);
// initialize the items list
return settingsView;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState)
{
super.onViewCreated(view, savedInstanceState);
// remove the dividers from the ListView of the ListFragment
settingsList = getListView();
settingsList.setDivider(null);
mItems = new ArrayList<SettingsCategories>();
Resources resources = getResources();
for(int c = 0; c < numCategories; c++)
{
mItems.add(new SettingsCategories(CategoryArray[c],resIds[c]));
}
// initialize and set the list adapter
// settingsAdapter = new SettingsAdapter(this.getActivity(), mItems);
setListAdapter(new SettingsAdapter(getActivity(), mItems));
settingsList.setAdapter(settingsAdapter);
}
public Settings()
{
this.numCategories = CategoryArray.length;
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
#Override
public boolean onLongClick(View v)
{
return false;
}
#Override
public void onListItemClick(ListView l, View v, int position, long id)
{
Object i = l.getItemAtPosition(position);
}
public class SettingsCategories
{
private String settingText;
private int imgResId;
SettingsCategories(String settingText,int imgResId)
{
this.settingText = settingText;
this.imgResId = imgResId;
}
public String getSettingText()
{
return this.settingText;
}
public int getImgResId()
{
return this.imgResId;
}
}
}
and finally these are my xml layouts (the first one is the main view and the second one is the view of a single item in the list
<?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="fill_parent"
android:orientation="vertical"
>
<SearchView
android:id="#+id/searchFunction"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
</SearchView>
<ListView
android:id="#android:id/list"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</ListView>
</RelativeLayout>
this represents an individual item in the list
<?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"
>
<ImageView
android:layout_width="52dp"
android:layout_height="52dp"
android:id="#+id/settingCategoryImg"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="52dp"
android:text=""
android:id="#+id/settingCategoryName"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/settingCategoryImg"
/>
</RelativeLayout>
You are setting null adapter so it is not refreshing.
you are commented initialization part
check in the following method:
#Override
public void onViewCreated(View view, Bundle savedInstanceState)
{
super.onViewCreated(view, savedInstanceState);
// remove the dividers from the ListView of the ListFragment
settingsList = getListView();
settingsList.setDivider(null);
mItems = new ArrayList<SettingsCategories>();
Resources resources = getResources();
for(int c = 0; c < numCategories; c++)
{
mItems.add(new SettingsCategories(CategoryArray[c],resIds[c]));
}
// initialize and set the list adapter
// settingsAdapter = new SettingsAdapter(this.getActivity(), mItems);
setListAdapter(new SettingsAdapter(getActivity(), mItems));
settingsList.setAdapter(settingsAdapter);
}
Your are using ListFragement and again inflating layout. that is not a good idea. when you are extending listfragment then inflating the layout is not required and and modify above method like:
#Override
public void onViewCreated(View view, Bundle savedInstanceState)
{
super.onViewCreated(view, savedInstanceState);
// remove the dividers from the ListView of the ListFragment
settingsList = getListView();
settingsList.setDivider(null);
mItems = new ArrayList<SettingsCategories>();
Resources resources = getResources();
for(int c = 0; c < numCategories; c++)
{
mItems.add(new SettingsCategories(CategoryArray[c],resIds[c]));
}
// initialize and set the list adapter
settingsAdapter = new SettingsAdapter(this.getActivity(), mItems);
//setListAdapter(new SettingsAdapter(getActivity(), mItems));
settingsList.setAdapter(settingsAdapter);
}

How to display arraylist in gridview in android

I want to display Arraylist items in Gridview. My Arraylist is like this :
1 Hello Hello
2 Hello Hello
If I bind it to a gridview control like this :
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, event_list);
gridview.setAdapter(adapter);
event_List is my Arraylist. Through this approach I get a complete Arraylist row or record in a cell of gridview . I want to display each item like "Hello" of Arraylist in each cell of gridview. Like 1 in one cell , "Hello" in another cell and so on.
Thanks in advance
Seems You need to use BaseAdapter, because default ArrayAdapter is not able to accomplish dividing of ArrayList element into number of elements.
So, it would look like the following:
public class MyActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final GridView grid = (GridView) findViewById(R.id.gridView);
final ArrayList<String> items = new ArrayList<String>();
items.add("1 , Hello11 , Hello12");
items.add("2 , Hello21 , Hello22");
grid.setAdapter(new GridAdapter(items));
}
// Assume it's known
private static final int ROW_ITEMS = 3;
private static final class GridAdapter extends BaseAdapter {
final ArrayList<String> mItems;
final int mCount;
/**
* Default constructor
* #param items to fill data to
*/
private GridAdapter(final ArrayList<String> items) {
mCount = items.size() * ROW_ITEMS;
mItems = new ArrayList<String>(mCount);
// for small size of items it's ok to do it here, sync way
for (String item : items) {
// get separate string parts, divided by ,
final String[] parts = item.split(",");
// remove spaces from parts
for (String part : parts) {
part.replace(" ", "");
mItems.add(part);
}
}
}
#Override
public int getCount() {
return mCount;
}
#Override
public Object getItem(final int position) {
return mItems.get(position);
}
#Override
public long getItemId(final int position) {
return position;
}
#Override
public View getView(final int position, final View convertView, final ViewGroup parent) {
View view = convertView;
if (view == null) {
view = LayoutInflater.from(parent.getContext()).inflate(android.R.layout.simple_list_item_1, parent, false);
}
final TextView text = (TextView) view.findViewById(android.R.id.text1);
text.setText(mItems.get(position));
return view;
}
}
}
Will produce grid with six items. See more in corresponding Android Guide for Grid View.
Or you maybe use this:
MainActivity.java:
import android.os.Bundle;
import android.app.Activity;
import android.support.annotation.NonNull;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
List<String> values=new ArrayList<String>();
values.add("Home");values.add("About");values.add("Contact");values.add("Help");values.add("Index");
values.add("Home");values.add("About");values.add("Contact");values.add("Help");values.add("Index");
GridView myGrid=(GridView)findViewById(R.id.grid);
myGrid.setAdapter(new ArrayAdapter<String>(this,R.layout.cell,values));
}
}
Your activity_main.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:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/mySelection" />
<GridView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/grid"
android:columnWidth="75dip"
android:gravity="center"
android:horizontalSpacing="5dip"
android:numColumns="auto_fit"
android:stretchMode="columnWidth"
android:verticalSpacing="75dip">
</GridView>
Create a new xml file in layout folder and name it cell.xml and put this in it:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="14sp">
Now run and enjoy. This is output:

ListView with RelativeLayout not highlighting background on press

I want to have a list of elements (using a ListView) and each element in list is styled with a relative layout. Currently, the items are being displayed correctly, however, for some reason the listview items dont glow green when they're clicked. Why is this?
I have removed all code to minimals and it still does this.
Activity class
package com.test;
import android.app.Activity;
public class My_ListView extends Activity
{
private ListView_Adapter listViewAdapter;
private ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.my_listview);
// initialise the list-view object
listViewAdapter = new ListView_Adapter(this);
listView = (ListView) findViewById(R.id.listview);
listView.setAdapter(listViewAdapter);
for (int i=0;i<20;i++)
{
listViewAdapter.add("item "+i);
}
}
public void clicked(View v)
{
v.setBackgroundColor(0xFF0000FF);
}
}
The listview item adapter class
package com.test;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class ListView_Adapter extends ArrayAdapter<String>
{
public ListView_Adapter(Context c)
{
super(c, R.layout.my_listview_item);
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
View row = convertView;
StationFinder_ListViewItemHolder holder = null;
if (row == null)
{
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.my_listview_item, parent, false);
holder = new StationFinder_ListViewItemHolder(row);
row.setTag(holder);
}
else
{
holder = (StationFinder_ListViewItemHolder) row.getTag();
}
holder.populateFrom(getItem(position));
return row;
}
static class StationFinder_ListViewItemHolder
{
private TextView destination = null;
StationFinder_ListViewItemHolder(View row)
{
destination = (TextView) row.findViewById(R.id.text1);
}
void populateFrom(String locationDistance)
{
destination.setText(locationDistance);
}
}
}
my_listview.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
>
<ListView android:id="#+id/listview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
</LinearLayout>
my_listview_item.xml
<?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="wrap_content"
android:onClick="clicked"
>
<TextView android:id="#+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</RelativeLayout>
I think you may have to call invalidate() after setting the background color.
You may want to do this instead by setting the listSelector and possibly drawSelectorOnTop for your ListView. That way the selection/deselection and clicks will be handled in the normal manner.
Edit - also, since you're using a ListView, you probably want to listen for clicks by setting an OnItemClickListener on your ListView.

Categories

Resources