I'm making a launcher for android with a feature where the user selects an alphabet, then apps starting with that alphabet will be displayed.
I'm having a class that stores name, icon, etc of apps and can successfully display it using Gridiew. But I can't seem to figure out how to display only the selected apps that starts with the selected alphabet.
MainActivity/Dashboard.java
public class Dashboard extends Activity {
DrawerAdapter drawerAdapterObject;
GridView drawerGrid;
class Pac {
Drawable icon;
String name;
String label;
}
Pac[] pacs;
PackageManager pm;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
drawerGrid = (GridView) findViewById(R.id.content);
pm = getPackageManager();
set_pacs();
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_PACKAGE_ADDED);
filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
filter.addDataScheme("package");
registerReceiver(new PacReciever(), filter);
}
public void set_pacs() {
final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
mainIntent.hasExtra("facebok");
List<ResolveInfo> pacsList = pm.queryIntentActivities(mainIntent, 0);
pacs = new Pac[pacsList.size()];
for(int i = 0; i < pacsList.size(); i++) {
pacs[i] = new Pac();
pacs[i].icon = pacsList.get(i).loadIcon(pm);
pacs[i].name = pacsList.get(i).activityInfo.packageName;
pacs[i].label = pacsList.get(i).loadLabel(pm).toString();
}
new SortApps().exchage_sort(pacs);
drawerAdapterObject = new DrawerAdapter(this, pacs);
drawerGrid.setAdapter(drawerAdapterObject);
drawerGrid.setOnItemClickListener(new DrawerClickListner(this, pacs, pm));
}
public class PacReciever extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
set_pacs();
}
}
public void test(){
Intent test = new Intent(this,MainActivity.class);
startActivity(test);
}
}
activity_dashboard.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_dashboard"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.zyconut.socio.Dashboard">
<SlidingDrawer
android:id="#+id/drawer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:handle="#+id/handle"
android:content="#+id/content"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
<ImageView
android:id="#+id/handle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#mipmap/ic_launcher"/>
<GridView
android:id="#+id/content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorPrimarytrans"
android:columnWidth="90dp"
android:numColumns="auto_fit"
android:verticalSpacing="50dp"
android:horizontalSpacing="50dp"/>
</SlidingDrawer>
</RelativeLayout>
DrawerAdapter.java
public class DrawerAdapter extends BaseAdapter {
Context mContext;
Dashboard.Pac[] pacsForAdapter;
public DrawerAdapter(Context c, Dashboard.Pac pacs[]) {
mContext = c;
pacsForAdapter = pacs;
}
#Override
public int getCount() {
return pacsForAdapter.length;
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
static class ViewHolder {
TextView text;
ImageView icon;
}
#Override
public View getView(int pos, View convertView, ViewGroup viewGroup) {
ViewHolder viewHolder;
LayoutInflater li = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if(convertView == null) {
convertView = li.inflate(R.layout.drawer_item, null);
viewHolder = new ViewHolder();
viewHolder.text = (TextView) convertView.findViewById(R.id.icon_text);
viewHolder.icon = (ImageView) convertView.findViewById(R.id.icon_image);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.icon.setImageDrawable(pacsForAdapter[pos].icon);
viewHolder.text.setText(pacsForAdapter[pos].label);
return convertView;
}
}
DrawerClickListner.java
public class DrawerClickListner implements OnItemClickListener {
Context mContext;
Dashboard.Pac[] pacsForAdapter;
PackageManager pmForListner;
public DrawerClickListner(Context c, Dashboard.Pac[] pacs, PackageManager pm) {
mContext = c;
pacsForAdapter = pacs;
pmForListner = pm;
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int pos, long l) {
Intent launchIntent = pmForListner.getLaunchIntentForPackage(pacsForAdapter[pos].name);
mContext.startActivity(launchIntent);
}
}
SortApps.java
public class SortApps {
public void exchage_sort(Dashboard.Pac[] pacs){
int i,j;
Dashboard.Pac temp;
for(i = 0; i < pacs.length; i++) {
for(j = i + 1; j < pacs.length; j++) {
if(pacs[i].label.compareToIgnoreCase(pacs[j].label) > 0) {
temp = pacs[i];
pacs[i] = pacs[j];
pacs[j] = temp;
}
}
}
}
}
drawer_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_horizontal">
<ImageView
android:id="#+id/icon_image"
android:layout_width="65dp"
android:layout_height="65dp"
android:padding="3dp"/>
<TextView
android:id="#+id/icon_text"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:maxLines="2"
android:gravity="center_horizontal"/>
</LinearLayout>
This is my first post, please do forgive me for any mistakes.
I just need someone to point me to how i can display apps starting with 'A' only. Rest I may be able to figure it out.
Thanks in advance
You can get the list of installed applications using the following snippet.
List<String> installedApps = new ArrayList<String>();
List<PackageInfo> packs = getPackageManager().getInstalledPackages(0);
for(int i=0;i<packs.size();i++) {
PackageInfo p = packs.get(i);
String appName = p.applicationInfo.loadLabel(getPackageManager()).toString();
installedApps.add(appName);
}
Then you can use this List to filter applications based on starting alphabet.
Related
I need to manage a ListView, so that each item has a textView and a RadioGroup. Following is the xml file for one item:
controls_layout_row.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:padding="20dp"
android:background="#drawable/fragment_template"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/control_name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#ffffff"
android:textSize="20sp"
android:textStyle="bold"
android:layout_marginBottom="5dp"/>
<RadioGroup
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/control_name"
android:id="#+id/control_options_list"
android:layout_marginBottom="20dp"
tools:layout_height="150dip">
<!-- items added within code -->
</RadioGroup>
</RelativeLayout>
The items are part of a ListView - following is the xml file for the ListView:
controls_dialog.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:padding="20dp"
android:background="#drawable/fragment_template"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/controls_list_title"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#ffffff"
android:text="Controls"
android:textSize="20dp"
android:textStyle="bold"
android:layout_marginBottom="5dp"/>
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/controls_list_title"
android:id="#+id/controls_list"
tools:layout_height="150dip">
<!-- items added within code -->
</ListView>
//Close button
<Button android:id="#+id/controls_close_button"
android:layout_below="#id/controls_list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="14dp"
android:text="Close"
android:layout_alignParentEnd="true"
android:textAllCaps="false"
android:textStyle="bold"/>
</RelativeLayout>
Now, the items are not known at the beginning. The application uses JNI interface to get info from connected hardware, and then some getters are used in the activity in order to know which items must appear in the dialog.
I have tried 2 methods, and I got stuck in both of them.
First method: simply create some item each time I need and add its view to the list:
// retrieve item view
final View emittersRowView = inflater.inflate(R.layout.controls_layout_row, null);
// set TextView
final TextView emitterTitle = emittersRowView.findViewById(R.id.control_name);
emitterTitle.setText("Projector");
//set RadioGroup
final String emitterDescriptions[] = getOptionDescriptions(Option.EMITTER_ENABLED);
final RadioGroup emittersRadioGroup = emittersRowView.findViewById(R.id.control_options_list);
// adding buttons to the group
for(int i = 0; i < emitterDescriptions.length; ++i) {
RadioButton button = new RadioButton(activity);
button.setId(i);
button.setText(emitterDescriptions[i]);
button.setTextColor(getResources().getColor(R.color.white));
button.setChecked(i == indexOfCurrentEmitter);
emittersRadioGroup.addView(button);
}
emittersRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener(){
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
List<Sensor> sensors = mDevice.querySensors();
for (Sensor s : sensors) {
if (s.supports(Option.EMITTER_ENABLED)) {
s.setValue(Option.EMITTER_ENABLED, checkedId);
}
}
}
});
//add control to list
ListView controlsList = fragmentView.findViewById(R.id.controls_list);
controlsList.addView(emittersRowView);
This method did not work. I have read in other forums that this cannot work without using an adpater. This seems weird to me, because using the addView method on the RadioGroup object, in order to add RadioButton objects works great.
Second Method: Using a Custom Adapter:
I have defined an adpater and my plan was to first build:
a String array for the TextView objects
a list of RadioGroup objects for the RadioGroup objects
and then use them for creating the adapter.
But when I got to the code, I got stuck, no knowing how to set the RadioGroup in the adapter:
Code for the adapter:
class CustomAdapter extends BaseAdapter {
#Override
public int getCount() {
return numOfControls;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final Activity activity = getActivity();
convertView = activity.getLayoutInflater().inflate(R.layout.controls_layout_row, null);
TextView control_name = convertView.findViewById(R.id.control_name);
RadioGroup control_options = convertView.findViewById(R.id.control_options_list);
control_name.setText(mControlNames[i]);
control_options.set....???
return convertView;
}
}
Please help me to make it work.
Start a new project and try below complete sample code,
MainActivity.java:
public class MainActivity extends AppCompatActivity {
class Control {
String name;
String[] options;
int checkedPosition = -1;
public Control(String name, String[] options) {
this.name = name;
this.options = options;
}
public String getName() {
return name;
}
public String[] getOptions() {
return options;
}
public int getCheckedPosition() {
return checkedPosition;
}
public void setCheckedPosition(int checkedPosition) {
this.checkedPosition = checkedPosition;
}
}
Control[] controls = new Control[10];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView controlsList = findViewById(R.id.controls_list);
createSampleData();
CustomAdapter adapter = new CustomAdapter(this, 0, controls);
controlsList.setAdapter(adapter);
Button button = findViewById(R.id.controls_close_button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String msg = "";
for (int i = 0; i < controls.length; i++) {
msg += controls[i].getName() + " , " + controls[i].getCheckedPosition() + "\n";
}
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
}
});
}
private void createSampleData() {
Random random = new Random();
for (int i = 0; i < controls.length; i++) {
int j = random.nextInt(4) + 2;
String[] options = new String[j];
for (int k = 0; k < j; k++) {
options[k] = (i + 1) + "-" + k;
}
controls[i] = new Control("Control " + (i + 1), options);
}
}
}
CustomAdapter.java:
public class CustomAdapter extends ArrayAdapter {
Context context;
LayoutInflater inflater;
public CustomAdapter(#NonNull Context context, int resource, #NonNull MainActivity.Control[] objects) {
super(context, resource, objects);
this.context = context;
inflater = LayoutInflater.from(context);
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
convertView = inflater.inflate(R.layout.controls_layout_row, null);
TextView control_name = convertView.findViewById(R.id.control_name);
RadioGroup control_options = convertView.findViewById(R.id.control_options_list);
MainActivity.Control control = (MainActivity.Control)getItem(position);
control_name.setText(control.getName());
String[] options = control.getOptions();
for(int i = 0; i < options.length; i++) {
RadioButton button = new RadioButton(context);
button.setId(i);
button.setText(options[i]);
button.setTextColor(Color.WHITE);
button.setChecked(i == control.getCheckedPosition());
control_options.addView(button);
}
control_options.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
int pos = (int)radioGroup.getTag();
MainActivity.Control changedControl = (MainActivity.Control)getItem(pos);
changedControl.setCheckedPosition(i);
}
});
control_options.setTag(position);
return convertView;
}
}
use your posted layouts.
This is my wordAdapter. It is not showing any result when I open the Fragment. Please help me as I am a novice android developer. The Fragment page is empty and it is also not showing any error while running. So, please tell what am I missing and what is the problem in this code.
public class wordAdapter extends ArrayAdapter<word> {
private Context context;
private List<word> wrd;
private SharedPreference sharedPreference;
public wordAdapter(Context context, List<word> wrd) {
super(context, R.layout.item, wrd);
this.context = context;
this.wrd = wrd;
sharedPreference = new SharedPreference();
}
private class ViewHolder {
TextView productNameTxt;
TextView productTypeTxt;
ImageView favoriteImg;
}
#Override
public int getCount() {
return wrd.size();
}
#Override
public word getItem(int position) {
return wrd.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.item, null);
holder = new ViewHolder();
holder.productNameTxt = (TextView) convertView
.findViewById(R.id.carname);
holder.productTypeTxt = (TextView) convertView
.findViewById(R.id.cartype);
holder.favoriteImg = (ImageView) convertView
.findViewById(R.id.favu);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
word wrdn = (word) getItem(position);
holder.productNameTxt.setText(wrdn.getName());
holder.productTypeTxt.setText(wrdn.getType());
/*If a product exists in shared preferences then set heart_red drawable
* and set a tag*/
if (checkFavoriteItem(wrdn)) {
holder.favoriteImg.setImageResource(R.drawable.fav);
holder.favoriteImg.setTag("red");
} else {
holder.favoriteImg.setImageResource(R.drawable.unfav);
holder.favoriteImg.setTag("grey");
}
return convertView;
}
/*Checks whether a particular product exists in SharedPreferences*/
private boolean checkFavoriteItem(word checkwrdn) {
boolean check = false;
List<word> favorites = sharedPreference.getFavorites(context);
if (favorites != null) {
for (word wrdn : favorites) {
if (wrdn.equals(checkwrdn)) {
check = true;
break;
}
}
}
return check;
}
#Override
public void add(word wrdn) {
super.add(wrdn);
wrd.add(wrdn);
notifyDataSetChanged();
}
#Override
public void remove(word wrdn) {
super.remove(wrdn);
wrd.remove(wrdn);
notifyDataSetChanged();
}
}
This is my word file.
public class word {
private String name;
private String type;
public word(String name, String type) {
super();
this.name = name;
this.type = type;
}
public String getName() {
return name;
}
public String getType() {
return type;
}
}
This is my Fragment file with the data.
public class Cars extends android.support.v4.app.Fragment implements
AdapterView.OnItemClickListener,
AdapterView.OnItemLongClickListener {
public static final String ARG_PAGE = "ARG_PAGE";
public static Favourites newInstance(int page) {
Bundle args = new Bundle();
args.putInt(ARG_PAGE, page);
Favourites fragment = new Favourites();
fragment.setArguments(args);
return fragment;
}
Activity activity;
ListView productListView;
List<word> wrds;
wordAdapter wrdAdapter;
SharedPreference sharedPreference;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activity = getActivity();
sharedPreference = new SharedPreference();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.list, container,
false);
findViewsById(view);
setProducts();
wrdAdapter = new wordAdapter(activity, wrds);
productListView.setAdapter(wrdAdapter);
productListView.setOnItemClickListener(this);
productListView.setOnItemLongClickListener(this);
return view;
}
private void setProducts() {
word product1 = new word("Lamborghini Huracan", "Sport");
word product2 = new word("Lamborghini Aventador", "Sport");
word product3 = new word("Jaguar XF", "Luxury Sedan");
word product4 = new word("Audi A4", "Luxury Sedan");
word product5 = new word("Ferrari 488", "Sport");
word product6 = new word("BMW i8", "Hybrid Sport");
word product7 = new word("Audi TT", "Sport");
wrds = new ArrayList<word>();
wrds.add(product1);
wrds.add(product2);
wrds.add(product3);
wrds.add(product4);
wrds.add(product5);
wrds.add(product6);
wrds.add(product7);
}
private void findViewsById(View view) {
productListView = (ListView) view.findViewById(R.id.list_product);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
word product = (word) parent.getItemAtPosition(position);
Toast.makeText(activity, product.toString(), Toast.LENGTH_LONG).show();
}
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View view,
int position, long arg3) {
ImageView button = (ImageView) view.findViewById(R.id.favu);
String tag = button.getTag().toString();
if (tag.equalsIgnoreCase("grey")) {
sharedPreference.addFavorite(activity, wrds.get(position));
button.setTag("red");
button.setImageResource(R.drawable.fav);
} else {
sharedPreference.removeFavorite(activity, wrds.get(position));
button.setTag("grey");
button.setImageResource(R.drawable.unfav);
}
return true;
}
#Override
public void onResume() {
getActivity().setTitle(R.string.app_name);
getActivity().getActionBar().setTitle(R.string.app_name);
super.onResume();
}
}
This is my list view.
<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:background="#EDEDED" >
<ListView
android:id="#+id/list_product"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:dividerHeight="10dp"
android:drawSelectorOnTop="true"
android:footerDividersEnabled="false"
android:padding="10dp"
android:scrollbarStyle="outsideOverlay" >
</ListView>
</RelativeLayout>
This is the items view.
<?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:descendantFocusability="blocksDescendants" >
<RelativeLayout
android:id="#+id/pdt_layout_item"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/carname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="6dp" />
<TextView
android:id="#+id/cartype"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/carname"
android:padding="6dp" />
<ImageView
android:id="#+id/favu"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_marginRight="3dp"
android:background="#null" />
</RelativeLayout>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_below="#id/pdt_layout_item"/>
</RelativeLayout>
I am try to update data from edit-text and spinner to my database . but I found problem when scrolling list-view and also update data. My data is fluctuation after scrolling , so enable to save updated data.
below is my demo code.. please tall me where I am wrong.
Activity code:(MainActivity.java)
public class MainActivity extends AppCompatActivity {
private ListView listview;
private MainActivity context;
private newCustomDBAdapter adpter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String main[] = {"A", "B", "C", "D", "E", "F", "G", "H","i", "j", "k", "l"};
String main1[] = {"Aa", "Bbb", "Cccc", "Ddddd", "Eeeeeee", "Fff", "G", "H","Eeeeeee", "Fff", "G", "H"};
String values[] = {"A1", "B2", "C3", "D4", "E4", "F6", "G7", "H8","E4", "F6", "G7", "H8"};
String values_temp[] = {"A1", "B2"};
String valuesSpin[][] = {main, main, main, main1, main1, main1, main1, main,values_temp,values_temp,values_temp,values_temp};
ArrayList<String> arraylist_item = new ArrayList<String>(Arrays.<String>asList(main));
ArrayList<String> arraylist_item_values = new ArrayList<String>(Arrays.<String>asList(values));
ArrayList<String> arraylist_item1 = new ArrayList<String>(Arrays.<String>asList(main1));
List<List<String>> listOfLists = new ArrayList<List<String>>();
listOfLists.add(arraylist_item1);
listview = (ListView) findViewById(R.id.listview);
context = this;
adpter= new newCustomDBAdapter(context, arraylist_item, arraylist_item_values, listOfLists,valuesSpin);
listview.setAdapter(adpter);
}
public void Save(View view)
{
String s=adpter.main_hash_map.toString();
Log.i("Valiue of has map- "," "+s);
}
}
Adapter Code:(newCustomDBAdapter.java)
public class newCustomDBAdapter extends BaseAdapter {
private final String[][] valuesSpin;
public boolean checkData;
public int counter = 0;
private String LVL;
private Context CONTEXT;
private List<String> ITEMS = new ArrayList<>();
public static HashMap<Integer, String> main_hash_map= new HashMap<>();
private List<List<String>> VALUES = new ArrayList<>();
private List<String> TYPES = new ArrayList<>();
private List<String> DATATITLE = new ArrayList<>();
private List<String> DATAVALUE = new ArrayList<>();
private String finalvalueInValue = "";
private boolean checkUserComesInv;
private String spinnerValue = "";
private String sizeValue = "";
private String final_value;
private HashMap<Integer, Integer> mapRowSpinnerPos = new HashMap<>();
public newCustomDBAdapter(Context context, List<String> items, List<String> type, List<List<String>> spinner_values, String[][] valuesSpin) {
this.ITEMS = items;
this.CONTEXT = context;
this.valuesSpin = valuesSpin;
this.TYPES = type;
checkData = true;
counter = 0;
}
#Override
public int getCount() {
if (ITEMS != null && ITEMS.size() != 0) {
return ITEMS.size();
}
return 0;
}
#Override
public Object getItem(int position) {
return ITEMS.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
final ViewHolder holder;
String itemlevel = "";
if (convertView == null) {
holder = new ViewHolder();
LayoutInflater newInflate = (LayoutInflater) CONTEXT.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = newInflate.inflate(R.layout.custom_new_db_adapter_layout, null);
holder.editMain = (EditText) convertView.findViewById(R.id.custum_main_edit);
holder.imgMain = (ImageView) convertView.findViewById(R.id.custum_main_img);
holder.spinMain = (Spinner) convertView.findViewById(R.id.custum_main_spinner);
holder.txtMain = (TextView) convertView.findViewById(R.id.custum_main_desc);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
if ((ITEMS.get(position).equals("A") || ITEMS.get(position).equals("D") || ITEMS.get(position).equals("i") || ITEMS.get(position).equals("l"))) {
holder.editMain.setVisibility(View.GONE);
holder.editMain.setEnabled(false);
holder.spinMain.setVisibility(View.VISIBLE);
holder.spinMain.setEnabled(true);
} else if (ITEMS.get(position).equals("B")) {
holder.spinMain.setVisibility(View.VISIBLE);
holder.editMain.setEnabled(true);
holder.editMain.setVisibility(View.VISIBLE);
holder.spinMain.setEnabled(true);
} else {
holder.editMain.setVisibility(View.VISIBLE);
holder.editMain.setEnabled(true); holder.spinMain.setVisibility(View.GONE);
holder.spinMain.setEnabled(false);
}
holder.txtMain.setText(ITEMS.get(position));
holder.editMain.setText(TYPES.get(position));
holder.editMain.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int arg1, int arg2, int arg3) {
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
}
#Override
public void afterTextChanged(Editable arg0) {
main_hash_map.put(position, arg0.toString());
Log.i("value edit- ",arg0.toString()+" position- "+position);
}
});
/* if (main_hash_map.containsKey(position)) {
holder.editMain.setText(main_hash_map.get(position));
}*/
holder.spinMain.setAdapter(new ArrayAdapter<>(CONTEXT, android.R.layout.simple_spinner_dropdown_item, valuesSpin[position]));
holder.spinMain.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int spinnerPosition, long id) {
mapRowSpinnerPos.put(position, spinnerPosition);
String textSpin = holder.spinMain.getSelectedItem().toString();
main_hash_map.put(position,textSpin
);
Log.i("value in spinner- ",textSpin+" position- "+position);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
if (mapRowSpinnerPos.containsKey(position)) {
holder.spinMain.setSelection(mapRowSpinnerPos.get(position));
}
return convertView;
}
public class
ViewHolder {
private EditText editMain;
private ImageView imgMain;
private TextView txtMain;
private Spinner spinMain;
String typeValue = "";
}
}
custom_new_db_adapter_layout.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">
<LinearLayout
android:orientation="horizontal"
android:layout_marginTop="5dp"
android:id="#+id/custum_main_lin_layout"
android:layout_width="match_parent"
android:background="#color/colorAccent"
android:layout_height="55dp">
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.3"
android:id="#+id/custum_main_desc"
android:textSize="18sp"
android:layout_margin="5dp"
android:textColor="#fff"
android:text=" ggggg"
android:layout_gravity="center_vertical"/>
<EditText android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.4"
android:singleLine="true"
android:lines="1"
android:inputType="text"
android:id="#+id/custum_main_edit"
android:layout_gravity="center_vertical"
android:maxLines="1"
android:background="#fff"
android:textColor="#000"
android:layout_margin="5dp"/>
<Spinner android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.7"
android:layout_margin="5dp"
android:visibility="visible"
android:background="#drawable/btn_dropdown_selected"
android:id="#+id/custum_main_spinner"
android:layout_gravity="center_vertical"/>
<ImageView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.1"
android:id="#+id/custum_main_img"
android:layout_gravity="center_vertical"
android:src="#drawable/icon_forward_10"/>
</LinearLayout>
</RelativeLayout>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android: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.newf.phoenixbd.demoaccornford.MainActivity">
<ListView
android:id="#+id/listview"
android:layout_width="match_parent"
android:layout_height="400dp"
android:layout_above="#+id/button"></ListView>
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save"
android:id="#+id/button"
android:onClick="Save"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
Sorry for my English.
thanks in advance.
You can pass the updated value from the adapter to your activity using an interface. I solved my problem using this:
Class:
public class YourActivity extends ActionBarActivity implements GetClickedItem {
Context mContext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Context mContext = this;
ListView Your_List = findViewById(R.id.listview);
Your_Adapter adptr = new Your_Adapter(mContext, (GetClickedItem) this);
Your_List.setAdapter(adptr);
}
#Override
public void getPostID(int position, String any_data) {
Toast(context, "position: " + position + " any_data: " + any_data).show();
}
}
and Adapter:
public class Your_Adapter extends BaseAdapter{
private Context mContext;
private GetClickedItem mGetClickedItem;
Holder holder;
// Constructor
public Your_Adapter(Context context, GetClickedItem itemclickreference) {
mContext = context;
this.mGetClickedItem = itemclickreference;
}
public int getCount() {
return your_data_size;
}
public Object getItem(int position) {
return your_data.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
holder = new Holder();
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater) mContext.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.xml_layout, null);
holder.mButton = (Button) convertView.findViewById(R.id.button);
convertView.setTag(holder);
}else {
holder = (Holder) convertView.getTag();
}
holder.mButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mGetClickedItem.getPostID(position, your_data.get(position));
}
});
return convertView;
}
public class Holder{
Button mButton;
}
public interface GetClickedItem{
public void getPostID(int position, String any_other_data);
}
}
You can access any data from the adapter, all you have to do is include the button in your adapter layout file.
I'm learning Android SDK and I need some advices.
I have custom ListView with BaseAdapter and I want to implement some new feature - Favorite Button.
What I want to do is, when I press the Favorite Button, ListItem goes to the beginning of the list, Favorite image change and all that stuff will be saved in the SharedPrefs.
Someone tell me what I need to do, to make it works?
my existing code:
row.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/layout_element_list"
>
<ImageView
android:id="#+id/icon"
android:layout_width="150dp"
android:padding="5dp"
android:layout_height="150dp"
android:layout_marginLeft="4px"
android:layout_marginRight="10px"
android:layout_marginTop="4px"
android:src="#drawable/radio" >
</ImageView>
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="#+id/label"
android:paddingTop="20dp"
android:layout_gravity="center_vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:textAlignment="center"
android:text="RadioName"
android:textColor="#color/color1"
android:textSize="30dp" />
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1">
<TextView
android:id="#+id/label2"
android:layout_gravity="center_vertical"
android:layout_width="fill_parent"
android:layout_weight="1"
android:layout_height="fill_parent"
android:textAlignment="center"
android:text="Description.."
android:textColor="#color/color1"
android:textSize="15dp" />
<ImageView
android:id="#+id/favButton"
android:layout_weight="1"
android:layout_width="fill_parent"
android:padding="5dp"
android:layout_height="fill_parent"
android:layout_marginLeft="4px"
android:layout_marginRight="10px"
android:layout_marginTop="4px"
android:src="#drawable/fav_off" >
</ImageView>
</LinearLayout>
</LinearLayout>
</LinearLayout>
BaseAdapter class:
public class RadioAdapter extends BaseAdapter
{
ArrayList<RadioStation> myList = new ArrayList<RadioStation>();
LayoutInflater inflater;
Context context;
public RadioAdapter(Context context, ArrayList<RadioStation> myList) {
this.myList = myList;
this.context = context;
inflater = LayoutInflater.from(this.context);
}
#Override
public int getCount() {
return myList.size();
}
#Override
public RadioStation getItem(int position) {
return myList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
MyViewHolder mViewHolder;
if(convertView == null) {
convertView = inflater.inflate(R.layout.activity_menu_row, null);
mViewHolder = new MyViewHolder();
convertView.setTag(mViewHolder);
} else {
mViewHolder = (MyViewHolder) convertView.getTag();
}
mViewHolder.tvTitle = detail(convertView, R.id.label, myList.get(position).getTitle());
mViewHolder.tvDesc = detail(convertView, R.id.label2, myList.get(position).getDescription());
mViewHolder.ivIcon = detail(convertView, R.id.icon, myList.get(position).getImgResId());
return convertView;
}
private TextView detail(View v, int resId, String text) {
TextView tv = (TextView) v.findViewById(resId);
tv.setText(text);
return tv;
}
private ImageView detail(View v, int resId, int icon) {
ImageView iv = (ImageView) v.findViewById(resId);
iv.setImageResource(icon); //
return iv;
}
private class MyViewHolder {
TextView tvTitle, tvDesc;
ImageView ivIcon;
}
}
RadioStation class:
public class RadioStation
{
public String title;
public String description;
public int imgResId;
//getters and setters
public static Comparator<RadioStation> comparatorByRadioName = new Comparator<RadioStation>()
{
#Override
public int compare(RadioStation radioStation, RadioStation radioStation2)
{
String name1 = radioStation.getTitle().toLowerCase();
String name2 = radioStation2.getTitle().toLowerCase();
return name1.compareTo(name2);
}
};
}
ActivityListView:
public class ActivityMenuList extends Activity implements AdapterView.OnItemClickListener
{
private ListView lvDetail;
private Context context = ActivityMenuList.this;
private ArrayList <RadioStation> myList = new ArrayList <RadioStation>();
private String[] names = new String[] { "one", "two", "three" };
private String[] descriptions = new String[] { "notset", "notset", "notset"};
private int[] images = new int[] { R.drawable.one, R.drawable.two, R.drawable.three };
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
getWindow().setBackgroundDrawableResource(R.drawable.bg1);
setContentView(R.layout.activity_menu_list);
lvDetail = (ListView) findViewById(R.id.list);
lvDetail.setOnItemClickListener(this);
getDataInList();
lvDetail.setAdapter(new RadioAdapter(context, myList));
}
private void getDataInList() {
for(int i=0;i<3;i++) {
RadioStation ld = new RadioStation();
ld.setTitle(names[i]);
ld.setDescription(descriptions[i]);
ld.setImgResId(images[i]);
myList.add(ld);
}
Collections.sort(myList, RadioStation.comparatorByRadioName);
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l)
{
String item = names[i];
Intent e = new Intent(ActivityMenuList.this, ActivityRadioStation.class);
Bundle data = new Bundle();
data.putString("radiostation",item);
e.putExtras(data);
startActivity(e);
}
}
That's a lot of changes you have to do. Let's start with the basic.
Add a boolean to your RadioStation for the favorite state.
public boolean isFavorite;
Next on your getView add the favorite button click listener(add its reference to the viewholder too, but let's keep it simple this time)
public class RadioAdapter extends BaseAdapter
{
ArrayList<RadioStation> myList = new ArrayList<RadioStation>();
LayoutInflater inflater;
Context context;
ListView mListview;
public RadioAdapter(Context context, ArrayList<RadioStation> myList, ListView list) {
this.myList = myList;
this.context = context;
mListView = list;
inflater = LayoutInflater.from(this.context);
}
#Override
public int getCount() {
return myList.size();
}
#Override
public RadioStation getItem(int position) {
return myList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
MyViewHolder mViewHolder;
if(convertView == null) {
convertView = inflater.inflate(R.layout.activity_menu_row, null);
mViewHolder = new MyViewHolder();
convertView.setTag(mViewHolder);
} else {
mViewHolder = (MyViewHolder) convertView.getTag();
}
mViewHolder.tvTitle = detail(convertView, R.id.label, myList.get(position).getTitle());
mViewHolder.tvDesc = detail(convertView, R.id.label2, myList.get(position).getDescription());
mViewHolder.ivIcon = detail(convertView, R.id.icon, myList.get(position).getImgResId());
convertView.findViewById(R.id.favButton).setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
myList.get(position).isFavorite=! myList.get(position).isFavorite;
//reorder mlist
notifyDataSetChanged();
//mListView. smoothscroll here
}
});
((ImageView) convertView.findViewById(R.id.favButton)).setImageResource(myList.get(position).isFavorite?R.drawable.favoriteOn:R.drawable.favoriteOff);
return convertView;
}
private TextView detail(View v, int resId, String text) {
TextView tv = (TextView) v.findViewById(resId);
tv.setText(text);
return tv;
}
private ImageView detail(View v, int resId, int icon) {
ImageView iv = (ImageView) v.findViewById(resId);
iv.setImageResource(icon); //
return iv;
}
private class MyViewHolder {
TextView tvTitle, tvDesc;
ImageView ivIcon;
}
}
I left commented what you should do on the listener. You should be able to continue from here.
When you create your adapter pass the list as the last parameter on the constructor.
Edited: Removed interface. No need to use it here.
I'm trying to make a custom tabbar with scrolling tabbar items.
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:orientation="vertical"
android:background="#drawable/bg"
tools:context=".MainActivity" >
<LinearLayout
android:id="#+id/main_tabbar"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:layout_below="#+id/main_rlTopbar" >
<FrameLayout
android:id="#+id/main_tabcontent"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1" />
<HorizontalScrollView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="0"
android:background="#drawable/bottombar" >
<LinearLayout
android:id="#+id/main_llTabs"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_gravity="center_vertical"
android:orientation="horizontal" >
</LinearLayout>
</HorizontalScrollView>
</LinearLayout>
</RelativeLayout>
mainactivity.java
...
m_scrollTabbar = new HScrollTabbar(this, R.id.main_tabcontent, R.id.main_llTabs);
m_scrollTabbar.addTab(null, 0, HomeActivity.class, true);
...
hscrolltabbar.java
public class HScrollTabbar {
private int m_nTabContentId = -1;
private int m_nScrollTabbarId = -1;
private Activity m_activityParent = null;
private ArrayList<ButtonTabbarItem> m_aryTabButton = new ArrayList<ButtonTabbarItem>();
private int m_nSelectedIndex = -1;
public void addTab(String labelId, int drawableId, Class<?> c) {
LinearLayout llTabs = (LinearLayout) m_activityParent.findViewById(m_nScrollTabbarId);
ButtonTabbarItem item = new ButtonTabbarItem(m_activityParent, c, m_aryTabButton.size());
llTabs.addView(item);
m_aryTabButton.add(item);
if (m_aryTabButton.size() == 1) {
setSelectedIndex(0);
}
item.setOnSelectTabListener(onSelectTabListener);
}
private OnSelectTabListener onSelectTabListener = new OnSelectTabListener() {
#Override
public void onSelect(int nSelectedIndex) {
setSelectedIndex(nSelectedIndex);
}
};
public void setSelectedIndex(int nIndex) {
if (m_nSelectedIndex == nIndex)
return;
ButtonTabbarItem item = null;
if (m_nSelectedIndex > -1) {
item = m_aryTabButton.get(m_nSelectedIndex);
item.setSelected(false);
}
m_nSelectedIndex = nIndex;
item = m_aryTabButton.get(m_nSelectedIndex);
item.setSelected(true);
FrameLayout frame = (FrameLayout) m_activityParent.findViewById(m_nTabContentId);
Intent intent = new Intent();
intent.setClass(frame.getContext(), item.getClassTarget());
frame.getContext().startActivity(intent);
}
public int getSelectedIndex() {
return m_nSelectedIndex;
}
}
buttontabbaritem.java
public class ButtonTabbarItem extends FrameLayout {
private static final int TAB_BTN_TAG = 100;
private Class<?> m_classTarget;
OnSelectTabListener m_listener = null;
public ButtonTabbarItem(Context context, Class<?> classTarget, int nIndex) {
super(context);
LinearLayout layout = new LinearLayout(context);
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.hscroll_tabbar_item, layout);
addView(view);
Button btn = (Button) view.findViewById(R.id.hscroll_tabbar_item_btn);
btn.setOnClickListener(onClickTab);
btn.setTag(TAB_BTN_TAG + nIndex);
m_classTarget = classTarget;
}
public Class<?> getClassTarget() {
return m_classTarget;
}
public void setClassTarget(Class<?> classTarget) {
m_classTarget = classTarget;
}
public void setSelected(boolean bSelected) {
if (bSelected) {
} else {
}
}
private OnClickListener onClickTab = new OnClickListener() {
#Override
public void onClick(View v) {
if (m_listener != null)
m_listener.onSelect((Integer) v.getTag() - TAB_BTN_TAG);
}
};
public interface OnSelectTabListener {
public void onSelect(int nSelectedIndex);
}
public void setOnSelectTabListener(OnSelectTabListener listener) {
m_listener = listener;
}
}
FrameLayout frame = (FrameLayout) m_activityParent.findViewById(m_nTabContentId);
Intent intent = new Intent();
intent.setClass(frame.getContext(), item.getClassTarget());
frame.getContext().startActivity(intent);
I'm trying to start activity inside frame, but it's not work.
Please help me.