I'm new to programming and I'm trying to make an application using Android Studio. So, what I want is something like this
Output I want:
And here's my code:
list_header.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="2dp"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:layout_width="45dp"
android:layout_height="45dp"
android:paddingBottom="20dp"
android:paddingLeft="20dp"
android:paddingTop="20dp"
android:id="#+id/iconimage"/>
<TextView
android:layout_width="match_parent"
android:layout_height="55dp"
android:padding="16dp"
android:textColor="#000000"
android:textSize="12sp"
android:id="#+id/submenu"
android:gravity="center_vertical" />
</LinearLayout>
list_submenu.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="16dp"
android:textColor="#000000"
android:layout_marginLeft="44dp"
android:textSize="12sp"
android:id="#+id/submenu"/>
</LinearLayout>
MainActivity.java
package com.example.mokui.hopeful;
import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.Layout;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ExpandableListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
View view_Group;
private DrawerLayout mDrawerLayout;
ExpandableListAdapter mMenuAdapter;
ExpandableListView expandableList;
List<String> listDataHeader;
HashMap<String, List<String>> listDataChild;
// icons
static int[] icon = {R.drawable.home, R.drawable.write};
#Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if(android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN_MR2) {
expandableList.setIndicatorBounds(expandableList.getRight()- 80, expandableList.getWidth());
} else {
expandableList.setIndicatorBoundsRelative(expandableList.getRight()- 80, expandableList.getWidth());
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
supportRequestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
//requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
expandableList = (ExpandableListView) findViewById(R.id.navigationmenu);
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
navigationView.setItemIconTintList(null);
/* ------------------------------EXPAND EXTENSION --------------------------------- */
if (navigationView != null) {
setupDrawerContent(navigationView);
}
prepareListData();
mMenuAdapter = new ExpandableListAdapter(this, listDataHeader, listDataChild);
// setting list adapter
expandableList.setAdapter(mMenuAdapter);
expandableList.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView expandableListView,
View view,
int groupPosition,
int childPosition, long id) {
//Log.d("DEBUG", "submenu item clicked");
Toast.makeText(MainActivity.this,
"Header: "+String.valueOf(groupPosition) +
"\nItem: "+ String.valueOf(childPosition), Toast.LENGTH_SHORT)
.show();
view.setSelected(true);
if (view_Group != null) {
view_Group.setBackgroundColor(Color.parseColor("#ffffff"));
}
view_Group = view;
view_Group.setBackgroundColor(Color.parseColor("#DDDDDD"));
mDrawerLayout.closeDrawers();
return false;
}
});
expandableList.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView expandableListView, View view, int i, long l) {
//Log.d("DEBUG", "heading clicked");
return false;
}
});
/* ------------------------------EXPAND EXTENSION --------------------------------- */
}
private void prepareListData() {
listDataHeader = new ArrayList<String>();
listDataChild = new HashMap<String, List<String>>();
// Adding data header
listDataHeader.add("Main Map");
listDataHeader.add("Create Post");
listDataHeader.add("Statistics");
listDataHeader.add("");
listDataHeader.add("Edit Account");
listDataHeader.add("Logout");
// listDataHeader.add("menu3");
// Adding child data
List<String> heading1 = new ArrayList<String>();
List<String> heading2 = new ArrayList<String>();
List<String> heading3 = new ArrayList<String>();
heading3.add("HeatMap and Graphs");
List<String> heading4 = new ArrayList<String>();
List<String> heading5 = new ArrayList<String>();
List<String> heading6 = new ArrayList<String>();
listDataChild.put(listDataHeader.get(0), heading1);// Header, Child data
listDataChild.put(listDataHeader.get(1), heading2);
listDataChild.put(listDataHeader.get(2), heading3);
listDataChild.put(listDataHeader.get(3), heading4);
listDataChild.put(listDataHeader.get(4), heading5);
listDataChild.put(listDataHeader.get(5), heading6);
} /* ---------------------------------------- */
private void setupDrawerContent(NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
menuItem.setChecked(true);
mDrawerLayout.closeDrawers();
return true;
}
});
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
/*
if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
} */
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
ExpandableListAdapter.xml
package com.example.mokui.hopeful;
import android.content.Context;
import android.graphics.Typeface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.HashMap;
import java.util.List;
public class ExpandableListAdapter extends BaseExpandableListAdapter {
private Context mContext;
private List<String> mListDataHeader; // header titles
// child data in format of header title, child title
private HashMap<String, List<String>> mListDataChild;
ExpandableListView expandList;
public ExpandableListAdapter(Context context,
List<String> listDataHeader,
HashMap<String,
List<String>> listChildData
// ,ExpandableListView mView
)
{
this.mContext = context;
this.mListDataHeader = listDataHeader;
this.mListDataChild = listChildData;
//this.expandList = mView;
}
#Override
public int getGroupCount() {
int i = mListDataHeader.size();
//Log.d("GROUPCOUNT", String.valueOf(i));
return i;
}
#Override
public int getChildrenCount(int groupPosition) {
return this.mListDataChild.get(
this.mListDataHeader.get(groupPosition))
.size();
}
#Override
public Object getGroup(int groupPosition) {
return this.mListDataHeader.get(groupPosition);
}
#Override
public Object getChild(int groupPosition, int childPosition) {
//Log.d("CHILD", mListDataChild.get(this.mListDataHeader.get(groupPosition))
// .get(childPosition).toString());
return this.mListDataChild.get(
this.mListDataHeader.get(groupPosition))
.get(childPosition);
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
String headerTitle = (String) getGroup(groupPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this.mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_header, null);
}
TextView lblListHeader = (TextView) convertView
.findViewById(R.id.submenu);
ImageView headerIcon = (ImageView) convertView.findViewById(R.id.iconimage);
lblListHeader.setTypeface(null, Typeface.BOLD);
lblListHeader.setText(headerTitle);
//lblListHeader.setText(headerTitle.getIconName());
// headerIcon.setImageResource(MainActivity.icon[groupPosition]);
return convertView;
}
#Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
final String childText = (String) getChild(groupPosition, childPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this.mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_submenu, null);
}
TextView txtListChild = (TextView) convertView
.findViewById(R.id.submenu);
txtListChild.setText(childText);
return convertView;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
But so far this is what I got: My current output result:
I just want the Statistics Option to be the only one that collapses. But mine turns out that everything is collapsable.
Hope this will help you...
You can use Linearlayout and provide animation to that linearlayout.
To expand the section, You just have to call this method inside your Statistics Option click listener :
llHidden.measure(MeasureSpec.EXACTLY, MeasureSpec.EXACTLY); // llHidden is the layout which will be GONE as visibility initially, later it will be visible inside Statistics Option.
expand1(llHidden, llHidden.getMeasuredHeight());
To collapse the section, You just have to call this method inside your Statistics Option click listener :
collapse1(llHidden);
/**
* To expand any view with smooth animation
*/
#SuppressLint("NewApi")
public static void expand1(final View v, final int height) {
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.HONEYCOMB) {
v.measure(LayoutParams.MATCH_PARENT, height);
final int targtetHeight = height;
v.getLayoutParams().height = 0;
v.setVisibility(View.VISIBLE);
Animation a = new Animation() {
#Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
v.getLayoutParams().height = interpolatedTime == 1 ? height
: (int) (targtetHeight * interpolatedTime);
v.requestLayout();
}
#Override
public boolean willChangeBounds() {
return false;
}
};
a.setDuration((int) (targtetHeight / v.getContext().getResources().getDisplayMetrics().density));
v.startAnimation(a);
} else {
v.setVisibility(View.VISIBLE);
final int widthSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
final int heightSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
v.measure(widthSpec, heightSpec);
ValueAnimator mAnimator = slideAnimator(0, v.getMeasuredHeight(), v);
mAnimator.start();
}
}
/**
* To Collapse any view with smooth animation
*/
#SuppressLint("NewApi")
public static void collapse1(final View v) {
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.HONEYCOMB) {
v.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
final int initialHeight = v.getMeasuredHeight();
Animation a = new Animation() {
#Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
if (interpolatedTime == 1) {
v.setVisibility(View.GONE);
} else {
v.getLayoutParams().height = initialHeight - (int) (initialHeight * interpolatedTime);
v.requestLayout();
}
}
#Override
public boolean willChangeBounds() {
return false;
}
};
a.setDuration((int) (initialHeight / v.getContext().getResources().getDisplayMetrics().density));
v.startAnimation(a);
} else {
int finalHeight = v.getHeight();
ValueAnimator mAnimator = slideAnimator(finalHeight, 0, v);
mAnimator.addListener(new Animator.AnimatorListener() {
#Override
public void onAnimationEnd(Animator animator) {
v.setVisibility(View.GONE);
}
#Override
public void onAnimationStart(Animator animation) {
}
#Override
public void onAnimationCancel(Animator animation) {
}
#Override
public void onAnimationRepeat(Animator animation) {
}
});
mAnimator.start();
}
}
Related
Hello friend please help me i am using Recylerview and implemented searchfilter but problem is that after searching the item in recylerview when i click on item it always return 0 position of the item i want actual position of list item please me help here is my code how get actual position recylerview after searching item in recylerview
here is my code
package bible.swordof.God;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, SearchView.OnQueryTextListener {
private ListView listView;
private ArrayList<String> books;
private ArrayList<String> bookid;
private ListViewAdapter adapter;
private DatabaseHelper mDBHelper = null;
private SQLiteDatabase mDb = null;
BookRecyclerAdopter bookRecyclerAdopter;
//life is awesome
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
setData();
RecyclerView bookanme = findViewById(R.id.list);
bookanme.setLayoutManager(new LinearLayoutManager(this));
bookRecyclerAdopter = new BookRecyclerAdopter(this, books);
bookanme.setAdapter(bookRecyclerAdopter);
/* adapter = new ListViewAdapter(MainActivity.this, R.layout.item_listview, books, bookid);
listView.setAdapter(adapter);*/
/* listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int booknumber=position;
String bookname=bookid.get(position);
Toast.makeText(MainActivity.this, ""+bookname, Toast.LENGTH_SHORT).show();
*//* Intent intent=new Intent(MainActivity.this,Chapters.class);
intent.putExtra("booknumber",booknumber);
intent.putExtra("bookname",bookname);
startActivity(intent);*//*
}
});
}
*/
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.search_voice_btn:
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(intent, 10);
} else {
Toast.makeText(this, "Your Device Don't Support Speech Input", Toast.LENGTH_SHORT).show();
}
break;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 10:
if (resultCode == RESULT_OK && data != null) {
ArrayList<String> result = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
Toast.makeText(this, "" + result.get(0), Toast.LENGTH_SHORT).show();
}
break;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
MenuItem myActionMenuItem = menu.findItem(R.id.action_search);
final SearchView searchView = (SearchView) MenuItemCompat.getActionView(myActionMenuItem);
searchView.setOnQueryTextListener(this);
return true;
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
Fragment fragment;
int id = item.getItemId();
if (id == R.id.home) {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
} else if (id == R.id.favoruite) {
Intent intent = new Intent(this, Favourite.class);
startActivity(intent);
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private void setData() {
books = new ArrayList<>();
bookid = new ArrayList<>();
mDBHelper = new DatabaseHelper(this);
mDb = mDBHelper.getReadableDatabase();
Cursor cursor = mDb.rawQuery("select b,n from key_english", new String[]{});
if (cursor != null && cursor.getCount() > 0) {
if (cursor.moveToFirst()) {
do {
books.add(cursor.getString(1));
bookid.add(cursor.getString(0));
} while (cursor.moveToNext());
}
}
}
#Override
public boolean onQueryTextSubmit(String s) {
return false;
}
#Override
public boolean onQueryTextChange(String newtext) {
String userinput = newtext.toLowerCase();
List<String> newlist = new ArrayList<>();
for (String name : books) {
if (name.toLowerCase().contains(userinput)) {
newlist.add(name);
}
}
bookRecyclerAdopter.updatelist(newlist);
return true;
}
}
package bible.swordof.God;
import android.app.Activity;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.amulyakhare.textdrawable.TextDrawable;
import com.amulyakhare.textdrawable.util.ColorGenerator;
import java.util.ArrayList;
import java.util.List;
public class BookRecyclerAdopter extends RecyclerView.Adapter<BookRecyclerAdopter.Booksholder>{
private List<String> bookname;
Context context;
public BookRecyclerAdopter(Context context,List<String> bookname) {
this.bookname = bookname;
this.context=context;
}
public class Booksholder extends RecyclerView.ViewHolder {
private ImageView imageView;
private TextView bookname;
public Booksholder(#NonNull View itemView) {
super(itemView);
imageView = (ImageView) itemView.findViewById(R.id.image_view);
bookname = (TextView) itemView.findViewById(R.id.text);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
}
#Override
public Booksholder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
LayoutInflater inflater = LayoutInflater.from(viewGroup.getContext());
View view = inflater.inflate(R.layout.item_listview, viewGroup, false);
return new Booksholder(view);
}
#Override
public void onBindViewHolder(#NonNull Booksholder booksholder, final int i) {
booksholder.bookname.setText(bookname.get(i));
//get first letter of each String item
String firstLetter = String.valueOf(bookname.get(i).charAt(0));
ColorGenerator generator = ColorGenerator.MATERIAL; // or use DEFAULT
// generate random color
int color = generator.getColor(bookname.get(i));
TextDrawable drawable = TextDrawable.builder()
.buildRound(firstLetter, color); // radius in px
booksholder.imageView.setImageDrawable(drawable);
}
#Override
public int getItemCount() {
return bookname.size();
}
public void updatelist(List<String>newlist){
bookname=new ArrayList<>();
bookname.addAll(newlist);
notifyDataSetChanged();
}
}
You will need to maintain a separate list of bookname. Let's call it filteredBookname. Initially set it as bookname.
public class BookRecyclerAdopter extends RecyclerView.Adapter<BookRecyclerAdopter.Booksholder>{
private List<String> bookname;
private List<String> filteredBookname;
Context context;
public BookRecyclerAdopter(Context context,List<String> bookname) {
this.bookname = bookname;
this.filteredBookname = bookname
this.context=context;
}
...
// other pieces of code.
and instead of using bookname to populate RecyclerView items, use filteredBookname
and your update list method will be,
public void updatelist(List<String>newlist){
filteredBookname=new ArrayList<>();
filteredBookname.addAll(newlist);
notifyDataSetChanged();
}
Using the above approach, you can always find the proper position of your item in the original list bookname
The reason is that you are picking the wrong list, pick your data from filtered adapter list/model.
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Books booksdata= (Books)adapterName.bookname.get(position);
Toast.makeText(MainActivity.this, ""+booksdata.bookname, Toast.LENGTH_SHORT).show();
Intent intent=new Intent(MainActivity.this,Chapters.class);
intent.putExtra("booknumber",booksdata.booknumber);
intent.putExtra("bookname",booksdata.bookname);
startActivity(intent);
}
});
}
holder.cardView_title.setOnClickListener {
when (holder.tv_number.text) {
"1" -> {
(context as Activity).startActivity(Intent(context, Ma1::class.java))
}
"2" -> {
(context as Activity).startActivity(Intent(context, Ma2::class.java))
}
"3" -> {
(context as Activity).startActivity(Intent(context, Ma3::class.java))
}
}
}
I Have problem to change background color of GroupView on position..
According to My Code
when i press 1nd number GroupView then the color change of 1st number GroupView.
AND
when i press 2nd number GroupView then 1st number GroupView is color is Changed.
I Want to change GroupView Color on Postion Expand and Collapse.
ExpandableListViewAdapter.java
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.NumberPicker;
import android.widget.TextView;
import com.acase.clouds.cloudstailor.Models.ExpandableModel;
import com.acase.clouds.cloudstailor.R;
import java.util.List;
public class ExpandableListViewAdapter extends BaseExpandableListAdapter {
private Context context;
private LayoutInflater inflater;
private List<ExpandableModel> listDataGroup;
public ExpandableListViewAdapter(Context context, List<ExpandableModel> listDataGroup) {
this.context = context;
this.listDataGroup = listDataGroup;
this.inflater = LayoutInflater.from(context);
}
#Override
public Object getChild(int groupPosition, int childPosititon) {
return listDataGroup.get(groupPosition);
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return 1;
}
#Override
public View getChildView(int groupPosition, final int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
ExpandableModel model = listDataGroup.get(groupPosition);
if (convertView == null) {
convertView = inflater.inflate(model.getLayoutId(), null);
}
switch (model.getType()) {
case AGE:
setNumberPicker(convertView, model);
break;
case STATE:
setNumberPicker(convertView, model);
break;
}
return convertView;
}
private void setNumberPicker(View convertView, final ExpandableModel model) {
NumberPicker numberPicker = convertView.findViewById(R.id.numberPicker);
numberPicker.setMinValue(0);
numberPicker.setMaxValue(99);
if (!model.getValue().isEmpty()) {
numberPicker.setValue(Integer.parseInt(model.getValue()));
}
// to change formate of number in numberpicker
numberPicker.setFormatter(new NumberPicker.Formatter() {
#Override
public String format(int i) {
return String.format("%02d", i);
}
});
numberPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker numberPicker, int i, int i1) {
model.setValue(i1 + "");
}
});
}
#Override
public int getChildrenCount(int groupPosition) {
return 1;
}
#Override
public Object getGroup(int groupPosition) {
return this.listDataGroup.get(groupPosition);
}
#Override
public int getGroupCount() {
return this.listDataGroup.size();
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
// String headerTitle = (String) getGroup(groupPosition);
if (convertView == null) {
convertView = inflater.inflate(R.layout.list_row_group, null);
}
ExpandableModel model = listDataGroup.get(groupPosition);
TextView tv_title = convertView.findViewById(R.id.tv_title);
TextView tv_value = convertView.findViewById(R.id.tv_value);
tv_title.setText(model.getName());
tv_value.setText(model.getValue());
return convertView;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
EditProfileActivity
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.acase.clouds.cloudstailor.Adapter.ExpandableListViewAdapter;
import com.acase.clouds.cloudstailor.Models.ExpandableModel;
import com.bumptech.glide.Glide;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class EditProfileActivity extends AppCompatActivity {
Toolbar toolbar;
ImageView profileimage;
TextView changephototext, textView;
RelativeLayout item;
private static final int PICK_IMAGE_REQUEST = 1;
public Uri path;
private ExpandableListView expandableListView;
private ExpandableListViewAdapter expandableListViewAdapter;
List<ExpandableModel> list = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_profile);
toolbar = findViewById(R.id.tool).findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Edit Profile");
profileimage = findViewById(R.id.Profile_Img);
profileimage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
fileChooser();
}
});
changephototext = findViewById(R.id.Change_Photo_Button);
changephototext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
fileChooser();
}
});
// initializing the views
initViews();
// initializing the listeners
initListeners();
// initializing the objects
initObjects();
}
private void initViews() {
expandableListView = findViewById(R.id.expandableListView);
}
private void initListeners() {
expandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
ExpandableModel model = list.get(groupPosition);
Toast.makeText(EditProfileActivity.this, model.getName() + " clicked at " + childPosition, Toast.LENGTH_SHORT).show();
return false;
}
});
expandableListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
#Override
public void onGroupExpand(int groupPosition) {
ExpandableModel model = list.get(groupPosition);
Toast.makeText(EditProfileActivity.this, model.getName() + " expanded", Toast.LENGTH_SHORT).show();
item = findViewById(R.id.Group);
item.setBackgroundResource(R.drawable.selectedlistback);
textView = findViewById(R.id.tv_title);
textView.setTextColor(getResources().getColor(R.color.colorPrimaryDark));
}
});
// ExpandableListView Group collapsed listener
expandableListView.setOnGroupCollapseListener(new ExpandableListView.OnGroupCollapseListener() {
#Override
public void onGroupCollapse(int groupPosition) {
ExpandableModel model = list.get(groupPosition);
Toast.makeText(EditProfileActivity.this, model.getName() + " collapsed", Toast.LENGTH_SHORT).show();
item = findViewById(R.id.Group);
item.setBackgroundResource(R.drawable.listback);
textView = findViewById(R.id.tv_title);
textView.setTextColor(getResources().getColor(R.color.colorAccent));
}
});
}
private void initObjects() {
ExpandableModel age = new ExpandableModel("AGE", "", ExpandableModel.ExpandableType.AGE, R.layout.list_row_child);
list.add(age);
ExpandableModel state = new ExpandableModel("STATE", "", ExpandableModel.ExpandableType.STATE, R.layout.list_row_child);
list.add(state);
expandableListViewAdapter = new ExpandableListViewAdapter(this, list);
expandableListView.setAdapter(expandableListViewAdapter);
}
private void fileChooser()
{
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, PICK_IMAGE_REQUEST);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data.getData() != null)
{
path = data.getData();
Glide.with(this).load(path).into(profileimage);
path = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(),path);
profileimage.setImageBitmap(bitmap);
}catch (IOException e){
e.printStackTrace();
}
}
}
}
Try add the following code inside getGroupView of your adapter:
if(isExpanded) {
convertView.setBackgroundResource(R.drawable.selectedlistback);
tv_title.setTextColor(context.getResources().getColor(R.color.colorPrimaryDark));
}else{
convertView.setBackgroundResource(R.drawable.listback);
tv_title.setTextColor(context.getResources().getColor(R.color.colorAccent));
}
and remove the listeners. Hope that helps!
I need to add onClick to the child items in ExpandableListView. I have reviewed other posts regarding this, but I could not integrate the code into mine, possibly due to a different variation of ExpandableListView codes.
It would be great if you can provide some in code explanation as well. Many thanks.
Here are my source codes:
activity_main.xml
`<?xml version="1.0" encoding="utf-8"?>
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=".MainActivity">
<ExpandableListView
android:id="#+id/expLV"
android:layout_width="match_parent"
android:layout_height="match_parent"></ExpandableListView>
</RelativeLayout>`
list_parent.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">
<TextView
android:id="#+id/listP"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="?
android:attr/expandableListPreferredItemPaddingLeft"
android:textSize="20dp"
android:paddingTop="20dp"
android:paddingBottom="20dp"
/>
</LinearLayout>
list_child.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="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/listC"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="?
android:attr/expandableListPreferredChildPaddingLeft"
android:textSize="14dp"
android:paddingBottom="20dp"
android:paddingTop="20dp"/>
</LinearLayout>
ExpandableListAdapter.java
package com.example.ehsan.myexplistview;
import android.content.Context;
import android.graphics.Typeface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.TextView;
import java.util.HashMap;
import java.util.List;
public class ExpandableListAdapter extends BaseExpandableListAdapter {
private Context context;
private List<String> listDataHeader;
private HashMap<String, List<String>> listHashMap;
public ExpandableListAdapter(Context context, List<String> listDataHeader, HashMap<String, List<String>> listHashMap) {
this.context = context;
this.listDataHeader = listDataHeader;
this.listHashMap = listHashMap;
}
#Override
public int getGroupCount() {
return listDataHeader.size();
}
#Override
public int getChildrenCount(int i) {
return listHashMap.get(listDataHeader.get(i)).size();
}
#Override
public Object getGroup(int i) {
return listDataHeader.get(i);
}
#Override
public Object getChild(int i, int i1) {
return listHashMap.get(listDataHeader.get(i)).get(i1);
}
#Override
public long getGroupId(int i) {
return i;
}
#Override
public long getChildId(int i, int i1) {
return i1;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public View getGroupView(int i, boolean b, View view, ViewGroup viewGroup) {
String parentText = (String)getGroup(i);
if (view == null)
{
LayoutInflater inflater = (LayoutInflater)this.context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
view=inflater.inflate(R.layout.list_parent, null);
}
TextView listP = (TextView)view.findViewById(R.id.listP);
listP.setTypeface(null, Typeface.BOLD);
listP.setText(parentText);
return view;
}
#Override
public View getChildView(int i, int i1, boolean b, View view, ViewGroup viewGroup) {
final String childText = (String)getChild(i,i1);
if (view == null)
{
LayoutInflater inflater = (LayoutInflater)this.context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
view=inflater.inflate(R.layout.list_child, null);
}
TextView listC = (TextView)view.findViewById(R.id.listC);
listC.setText(childText);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(i1==0){
Intent intent = new Intent(activity,OneTwoThree.class);
activity.startActivity(intent);
}
else if (i1 ==1){
Intent intent = new Intent(activity,FourFiveSix.class);
activity.startActivity(intent);
}
else if (i1 ==2){
Intent intent = new Intent(activity,SevenEightNine.class);
activity.startActivity(intent);}
else if (i1 ==3){
Intent intent = new Intent(activity,TenElevenTwelve.class);
activity.startActivity(intent);}
}
});
return view;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
MainActivity.java
package com.example.ehsan.myexplistview;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ExpandableListView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private ExpandableListView expandableListView;
private ExpandableListAdapter expandableListAdapter;
private List<String> listP;
private HashMap<String, List<String>> listC;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
expandableListView = (ExpandableListView)findViewById(R.id.expLV);
initData();
expandableListAdapter = new ExpandableListAdapter(this, listP, listC);
expandableListView.setAdapter(expandableListAdapter);
}
private void initData(){
listP = new ArrayList<>();
listC = new HashMap<>();
listP.add("ABC");
listP.add("DEF");
listP.add("GHI");
listP.add("JKL");
List <String> abc = new ArrayList<>();
abc.add("123");
List <String> def = new ArrayList<>();
def.add("456");
def.add("789");
List <String> ghi = new ArrayList<>();
ghi.add("101112");
ghi.add("131415");
ghi.add("161718");
List <String> jkl = new ArrayList<>();
jkl.add("192021");
jkl.add("222324");
jkl.add("252627");
jkl.add("282930");
listC.put(listP.get(0),abc);
listC.put(listP.get(1),def);
listC.put(listP.get(2),ghi);
listC.put(listP.get(3),jkl);
}
}
You can set child click of expandable list in two ways
1.write child click event inside the getChildView() method.
#Override
public View getChildView(final int groupPosition, final int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
Page page =(Page) getChild(groupPosition, childPosition);
convertView = inflater.inflate(R.layout.child_list_layout, null);
Button mButton=(Button)convertView.findViewById(R.id.button1);
mButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Your code goes here ....
}
});
return convertView;
}
2.write click directly from expandable listview.
mExpandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
#Override
public boolean onChildClick(
ExpandableListView parent, View v,
int groupPosition, int childPosition,
long id) {
GoCategory(mainMenusList.get(groupPosition)
.getPagesList().get(childPosition));
return false;
}
});
Iam beginner in Android Development , so i followed tutorial from http://www.androidhive.info/2015/04/android-getting-started-with-material-design/ , i would like to add icons to listview in android navigation drawerm, plz help me in fixing this
here is my nav_drawer_row.xml source :
<?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"
android:clickable="true">
<TextView
android:id="#+id/title"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="30dp"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:textSize="15dp"
android:textStyle="bold" />
</RelativeLayout>
Here is my NavigationDrawerAdapter.java source :
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.Collections;
import java.util.List;
/**
* Created by Ravi Tamada on 12-03-2015.
*/
public class NavigationDrawerAdapter extends RecyclerView.Adapter<NavigationDrawerAdapter.MyViewHolder> {
List<NavDrawerItem> data = Collections.emptyList();
private LayoutInflater inflater;
private Context context;
public NavigationDrawerAdapter(Context context, List<NavDrawerItem> data) {
this.context = context;
inflater = LayoutInflater.from(context);
this.data = data;
}
public void delete(int position) {
data.remove(position);
notifyItemRemoved(position);
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.nav_drawer_row, parent, false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
NavDrawerItem current = data.get(position);
holder.title.setText(current.getTitle());
}
#Override
public int getItemCount() {
return data.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
TextView title;
public MyViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.title);
}
}
}
Here is FragmentDrawer.java source:
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
import java.util.List;
import info.androidhive.materialdesign.R;
import info.androidhive.materialdesign.adapter.NavigationDrawerAdapter;
import info.androidhive.materialdesign.model.NavDrawerItem;
public class FragmentDrawer extends Fragment {
private static String TAG = FragmentDrawer.class.getSimpleName();
private RecyclerView recyclerView;
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private NavigationDrawerAdapter adapter;
private View containerView;
private static String[] titles = null;
private FragmentDrawerListener drawerListener;
public FragmentDrawer() {
}
public void setDrawerListener(FragmentDrawerListener listener) {
this.drawerListener = listener;
}
public static List<NavDrawerItem> getData() {
List<NavDrawerItem> data = new ArrayList<>();
// preparing navigation drawer items
for (int i = 0; i < titles.length; i++) {
NavDrawerItem navItem = new NavDrawerItem();
navItem.setTitle(titles[i]);
data.add(navItem);
}
return data;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// drawer labels
titles = getActivity().getResources().getStringArray(R.array.nav_drawer_labels);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflating view layout
View layout = inflater.inflate(R.layout.fragment_navigation_drawer, container, false);
recyclerView = (RecyclerView) layout.findViewById(R.id.drawerList);
adapter = new NavigationDrawerAdapter(getActivity(), getData());
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), recyclerView, new ClickListener() {
#Override
public void onClick(View view, int position) {
drawerListener.onDrawerItemSelected(view, position);
mDrawerLayout.closeDrawer(containerView);
}
#Override
public void onLongClick(View view, int position) {
}
}));
return layout;
}
public void setUp(int fragmentId, DrawerLayout drawerLayout, final Toolbar toolbar) {
containerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
mDrawerToggle = new ActionBarDrawerToggle(getActivity(), drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close) {
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getActivity().invalidateOptionsMenu();
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
getActivity().invalidateOptionsMenu();
}
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
super.onDrawerSlide(drawerView, slideOffset);
toolbar.setAlpha(1 - slideOffset / 2);
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerToggle.syncState();
}
});
}
public static interface ClickListener {
public void onClick(View view, int position);
public void onLongClick(View view, int position);
}
static class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {
private GestureDetector gestureDetector;
private ClickListener clickListener;
public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final ClickListener clickListener) {
this.clickListener = clickListener;
gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
#Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null) {
clickListener.onLongClick(child, recyclerView.getChildPosition(child));
}
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
clickListener.onClick(child, rv.getChildPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
public interface FragmentDrawerListener {
public void onDrawerItemSelected(View view, int position);
}
}
You need to make a custom layout for your Navigation Drawer. Then you will be able to add images and even expandable lists. Here is a tutorial for you.
http://www.tutecentral.com/android-custom-navigation-drawer
You can set drawableLeft property in xml.
Or you can set programatically.
You can use any of the following methods for setting the Drawable on TextView:
1- setCompoundDrawablesWithIntrinsicBounds(int, int, int, int)
2- setCompoundDrawables(Left_Drawable, Top_Drawable, Right_Drawable, Bottom_Drawable)
And to get drawable from resources you can use:
getResources().getDrawable(R.drawable.your_drawable_id);
Here is the library in question: https://github.com/astuetz/PagerSlidingTabStrip
I figure it has something to do with .setTypeface() but I have no idea how to use it. I put the font I want in the assets folder. Here's my code.
Start.java
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.Editable;
import android.util.TypedValue;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.astuetz.PagerSlidingTabStrip;
public class Start extends FragmentActivity {
private final Handler handler = new Handler();
private PagerSlidingTabStrip tabs;
private ViewPager pager;
private MyPagerAdapter adapter;
private int currentColor = 0xFF547CC1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
tabs = (PagerSlidingTabStrip) findViewById(R.id.tabs);
pager = (ViewPager) findViewById(R.id.pager);
adapter = new MyPagerAdapter(getSupportFragmentManager());
pager.setAdapter(adapter);
final int pageMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4, getResources()
.getDisplayMetrics());
pager.setPageMargin(pageMargin);
tabs.setViewPager(pager);
tabs.setIndicatorColor(currentColor);
/*Typeface tf = Typeface.createFromAsset(getAssets(), "RobotoCondensed-Regular.ttf");
tabs.setTypeface(tf,Typeface.NORMAL);*/
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.start, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}else if(id == R.id.add_location){
Toast.makeText(getApplicationContext(), "todo", Toast.LENGTH_SHORT).show();
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Enter a location");
alert.setMessage("Enter a zipcode or city");
final EditText input = new EditText(this);
alert.setView(input);
alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Editable value = input.getText();
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Canceled.
}
});
alert.show();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onSaveInstanceState(Bundle outState){
super.onSaveInstanceState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState){
super.onRestoreInstanceState(savedInstanceState);
}
private Drawable.Callback drawableCallback = new Drawable.Callback() {
#Override
public void invalidateDrawable(Drawable who) {
getActionBar().setBackgroundDrawable(who);
}
#Override
public void scheduleDrawable(Drawable who, Runnable what, long when) {
handler.postAtTime(what, when);
}
#Override
public void unscheduleDrawable(Drawable who, Runnable what) {
handler.removeCallbacks(what);
}
};
public class MyPagerAdapter extends FragmentPagerAdapter{
private final String[] TABS = {"Today", "This Week"};
public MyPagerAdapter(FragmentManager fm){
super(fm);
}
public CharSequence getPageTitle(int position){
return TABS[position];
}
#Override
public int getCount() {
return TABS.length;
}
#Override
public Fragment getItem(int position) {
return WeatherTabs.newInstance(position);
}
}
}
activity_start.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.astuetz.PagerSlidingTabStrip
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="48dip"
app:pstsShouldExpand="true" />
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/tabs"
tools:context=".Start" />
</RelativeLayout>
As you can see in Start.java, I have already tried to use .setTypeface() in the onCreate() method and it produces no errors, but when I run my app it crashes on startup so I'm not using .setTypeface() correctly.
add below code in your activity it works:
com.viewpagerindicator.TabPageIndicator indicator = (com.viewpagerindicator.TabPageIndicator) findViewById(R.id.tabs);
Typeface type = Typeface.createFromAsset(getAssets(),"fonts/BYekan+ Bold.ttf");
LinearLayout view = (LinearLayout) indicator.getChildAt(0);
int tabCount=3;
for(int i=0;i<tabCount;i++){
TextView textView = (TextView) view.getChildAt(i);
textView.setTypeface(type);
}
if you use this library :
https://github.com/jpardogo/PagerSlidingTabStrip
in PagerSlidingTabStrip class change line 185 :
mTabTextTypeface = Typeface.create(tabTextTypefaceName, mTabTextTypefaceStyle);
to this :
mTabTextTypeface = Typeface.create(Typeface.createFromAsset(context.getAssets(),"DroidNaskh.ttf"), mTabTextTypefaceStyle);
I ran into this a while back - without overriding ViewPager code there isn't a way to do this
I used PagerSlidingTabStrip lib and i set like this and it is worked for me
public void changeTabsFont( PagerSlidingTabStrip tabs)
{
try
{
Typeface tab_face;
tab_face = Typeface.create(Typeface.createFromAsset(activity.getAssets(), "font/NanumBarunGothic.ttf"), Typeface.NORMAL);
ViewGroup vg = (ViewGroup) tabs.getChildAt(0);
int tabsCount = vg.getChildCount();
for (int j = 0; j < tabsCount; j++)
{
ViewGroup vgTab = (ViewGroup) vg.getChildAt(j);
int tabChildsCount = vgTab.getChildCount();
for (int i = 0; i < tabChildsCount; i++)
{
View tabViewChild = vgTab.getChildAt(i);
if (tabViewChild instanceof TextView)
{
((TextView) tabViewChild).setTypeface(tab_face, Typeface.NORMAL);
}
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
}