Value for text alignment in style.xml for TextView - android

I try to create set of TextView programmatically but a want to customize each TextView by xml style. I create TextView instances and place it into LinearLayout.
In my style.xml script I add custom values for text size and color, and all work fine.
But I cant't set text alignment to center by my styles.xml file.
It's my java code snippet:
import android.view.View;
public class GramophoneForm extends AppCompatActivity
{
private LinearLayout m_button_container = null;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
....
....
m_button_container = this.findViewById(R.id.gr_view_container);
List<? extends Object> ct_list = getClassificationTypes();
setObjectsList(ct_list);
}
public void setObjectsList(List<? extends Object> objects)
{
m_button_container.removeAllViews();
for(Object o : objects)
{
TextView item = new TextView(this);
item.setTextAppearance(this, R.style.selectionTextStyle);
////////////////////Is't works fine, but I want set up text alignment by xml style
item.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
////////////////////
item.setText(o.toString());
item.setTag(o);
m_button_container.addView(item);
}
}
}
My styles.xml code snippet:
<style name="selectionTextStyle" parent="#android:style/Widget.TextView">
<item name="android:layout_width">match_parent</item>
<item name="android:textSize">25dp</item>
<item name="android:textColor">#FFFF00FF</item>
<item name="android:textStyle">bold</item>
<!-- don't work -->
<item name="android:layout_centerInParent">true</item>
<!-- don't work
<item name="android:textAlignment">4</item>
-->
<!--don't work
<item name="android:textAlignment">center</item>
-->
</style>

A possible solution for your problem is to create a XML layout with a TextView with the style applied to it, and instead of creating an instance of TextView every time, inflate the layout.
XML example, lets say its named myTextViewLayout:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="#style/selectionTextStyle" />
And in your for loop inflate it and add it to the container:
for(Object o : objects){
TextView item = (TextView)getLayoutInflater().inflate(R.layout.myTextViewLayout, null);
item.setText(o.toString());
item.setTag(o);
m_button_container.addView(item);
}

You should insert a dimension value within the style xml:
<dimen name="buttonHeight">40px</dimen>
Then you simply should reference the dimension value. So in your layout file you'll write:
android:layout_height="#dimen/buttonHeight"

change your parent attribute from this parent="#android:style/Widget.TextView" to this android:Widget.Material.Light.TextView hope it will work!

Related

Dynamic Spinner with icons inheriting AppCompat theme

I am trying to achieve two things:
Make my Spinners inherit from the AppCompat themes.
Add icons to the spinner elements, as is possible in the Toolbar popup menus.
Since I am not able to achieve the first point I am focusing on that, but I also want to add icons later on. As it is now, my Toolbar popup menus inherit the AppCompat theme, but the Spinners do not, as shown in the pictures below. The first image shows the (proper) popup menu from the Toolbar, while the second shows the popup menu from a Spinner. This is an example of a Spinner that is not inheriting the style. Or should this popup menu style be expected?
I have tried loads of things, so there are likely multiple duplicates of this question, but I am not able to make it work. What can be wrong in the code below? After the theme is inherited correctly, how can I add icons later on? Minimum SDK version is 16, target is 23.
themes.xml:
<resources>
<style name="MyTheme.Base" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
<item name="colorPrimary">#color/my_brown</item>
<item name="colorPrimaryDark">#color/my_dark_gray</item>
<item name="colorAccent">#color/my_green</item>
<!-- This is just a test, it makes no difference. -->
<item name="android:spinnerStyle">#style/MySpinnerStyle</item>
</style>
<style name="MyTheme" parent="MyTheme.Base"></style>
<!--
ActionBar style, applied directly to XML elements
-->
<style name="MyActionBarStyle" parent="#style/Widget.AppCompat.ActionBar">
<item name="theme">#style/ThemeOverlay.AppCompat.Dark.ActionBar</item>
<item name="popupTheme">#style/ThemeOverlay.AppCompat.Light</item>
<item name="android:layout_width">match_parent</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:background">#color/my_brown</item>
<item name="android:minHeight">?attr/actionBarSize</item>
</style>
<!--
Spinner style, for testing. Also tried applied directly to xml Spinners.
-->
<style name="MySpinnerStyle" parent="#style/Widget.AppCompat.Spinner">
<item name="popupTheme">#style/ThemeOverlay.AppCompat.Light</item>
<item name="android:popupMenuStyle">#style/Widget.AppCompat.Light.PopupMenu</item>
</style>
</resources>
The Spinner is set up as simply as:
ArrayAdapter<String> adapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_spinner_item, mCategories);
mSpinner.setAdapter(adapter);
where mSpinner is the inflated Spinner and mCategories is a String array. In XML the Spinner is defined as
<Spinner
android:id="#+id/my_spinner"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"/>
I have tried adding various styles directly to the Spinner, but it does not work.
In my AndroidManifest.xml I have added the following to the Application tag:
android:theme="#style/MyTheme"
I managed to do it (or to be very close to it) by changing themes and styles like that:
Just add to your theme:
<item name="android:spinnerDropDownItemStyle">#style/MySpinnerItem</item>
Then create a style for MySpinnerItem that inherits from Widget.AppCompat.DropDownItem.Spinner:
<style name="MySpinnerItem" parent="#style/Widget.AppCompat.DropDownItem.Spinner">
<item name="android:textColor">#color/your_text_color</item>
<item name="android:textSize">16sp</item>
<item name="android:paddingLeft">16dp</item>
<item name="android:paddingStart" tools:targetApi="jelly_bean_mr1">16dp</item>
<item name="android:paddingRight">16dp</item>
<item name="android:paddingEnd" tools:targetApi="jelly_bean_mr1">16dp</item>
</style>
That's it for the AppCompat theme.
Finally, if you want to add icons to list items, you have to create a custom layout and set it programmatically. You can follow this tutorial http://android-er.blogspot.sg/2010/12/custom-arrayadapter-for-spinner-with.html that explains it.
Basically you have to:
create a custom layout
create a custom adapter that inherits from ArrayAdapter
implements getCutomView() methods to set your different images for each item
finally set your adapter to the spinner with MyCustomAdapter.createFromResource(this, R.array.my_data, R.layout.my_cutom_item_layout);
The cause of my problem was in the line
ArrayAdapter<String> adapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_spinner_item, mCategories);
Here I am using android.R.layout.simple_spinner_item which is probably meant for the Spinner itself. Using android.R.layout.simple_spinner_dropdown_item instead gives the desired look for the dropdown items.
The difference between those are described in some detail in this question, though the images are for older Android versions.
For reference, here are the two layouts taken directly from the Android source code.
simple_spinner_item
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/text1"
style="?android:attr/spinnerItemStyle"
android:singleLine="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ellipsize="marquee"
android:textAlignment="inherit"/>
simple_spinner_dropdown_item
<CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/text1"
style="?android:attr/spinnerDropDownItemStyle"
android:singleLine="true"
android:layout_width="match_parent"
android:layout_height="?android:attr/dropdownListPreferredItemHeight"
android:ellipsize="marquee"/>
Adding icons to the dropdown items
Now, for the icon part, I followed the steps from #euitam and ended up with the following:
MyAdapter:
public class MyAdapter extends ArrayAdapter<String>
{
private String[] mCategories;
private int[] mIcons;
public CategoryDropDownAdapter(Context context, int layoutResourceId, String[] categories)
{
super(context, layoutResourceId, categories);
mCategories = categories;
// Add the same icon to all items, just for testing.
mIcons = new int[mCategories.length];
for (int i = 0; i < mIcons.length; i++)
{
mIcons[i] = R.drawable.my_icon;
}
}
/**
* View for a dropdown item.
* */
#Override
public View getDropDownView(int position, View convertView, ViewGroup parent)
{
View rowView = convertView;
if (rowView == null)
{
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
rowView = inflater.inflate(R.layout.my_spinner_categories_dropdown_item, parent, false);
}
TextView categoryText = (TextView) rowView.findViewById(R.id.my_spinner_dropdown_item_text);
categoryText.setText(mCategories[position]);
ImageView icon = (ImageView) rowView.findViewById(R.id.my_spinner_dropdown_item_icon);
icon.setImageResource(mIcons[position]);
return rowView;
}
/**
* The Spinner View that is selected and shown in the *Spinner*, i.e. not the dropdown item.
* */
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
View spinnerView = convertView;
if (spinnerView == null)
{
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
spinnerView = inflater.inflate(R.layout.my_spinner_categories_spinner_item, parent, false);
}
TextView categoryText = (TextView) spinnerView.findViewById(R.id.my_spinner_item_text);
categoryText.setText(mCategories[position]);
return spinnerView;
}
}
my_spinner_categories_dropdown_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<ImageView
android:id="#+id/my_spinner_dropdown_item_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<!-- Stolen from android.R.layout.simple_spinner_dropdown_item -->
<TextView
android:id="#+id/my_spinner_dropdown_item_text"
style="?android:attr/spinnerDropDownItemStyle"
android:singleLine="true"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ellipsize="marquee" />
</LinearLayout>
my_spinner_categories_spinner_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<!-- Stolen from android.R.layout.simple_spinner_dropdown_item -->
<TextView
android:id="#+id/my_spinner_item_text"
style="?android:attr/spinnerDropDownItemStyle"
android:singleLine="true"
android:layout_width="0dp"
android:layout_height="48dp"
android:layout_weight="1"
android:ellipsize="marquee" />
</LinearLayout>
And finally, setting the adapter:
MyAdapter adapter = new MyAdapter(getContext(), android.R.layout.simple_spinner_dropdown_item, mCategories);
mSpinner.setAdapter(adapter);

Fullscreen DialogFragment with translucent StatusBar

I have a DialogFragment which I want to show in fullscreen. I do however still want a StatusBar present, and the hardware buttons at the bottom. I also want to set a background color of the StatusBar (for Lollipop).
My problem is that if I set the following flags in the DialogFragment:
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
Both the StatusBar and Hardware keyboard becomes translucent, and the DialogFragment stretches behind these.
Here is the code, which has been greatly reduced to become readable:
public class CardDetailsDialog extends DialogFragment {
Setup parameters...
public static CardDetailsDialog newInstance(final long cardId, final long projectId){
CardDetailsDialog frag = new CardDetailsDialog();
frag.setStyle(DialogFragment.STYLE_NORMAL, R.style.CardDetailsDialogStyle);
return frag;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if(getDialog() != null) {
getDialog().getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
getDialog().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
getDialog().getWindow().getAttributes().windowAnimations = R.style.DialogSlideAnimation;
getDialog().getWindow().setLayout(LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
getDialog().getWindow().setStatusBarColor(Color.RED);
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.card_details, container, false);
Handle everything that happens inside the view...
return view;
}
}
Here is the referred theme:
<style name="CardDetailsDialogStyle" parent="#style/Theme.AppCompat.Light.Dialog" >
<item name="android:windowBackground">#null</item>
<item name="android:windowNoTitle">true</item>
<item name="android:windowFrame">#null</item>
<item name="android:windowIsFloating">true</item>
<item name="android:windowContentOverlay">#null</item>
<item name="android:windowAnimationStyle">#android:style/Animation.Dialog</item>
<item name="android:windowSoftInputMode">stateUnspecified|adjustPan</item>
</style>
And the style of the fragment:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/pp.whiteBackgroundColor" >
<android.support.v7.widget.Toolbar xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/card_details_toolbar"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_alignParentTop="true"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/PopupMenutheme">
</android.support.v7.widget.Toolbar>
<ScrollView
android:id="#+id/details_scrollview"
android:layout_height="wrap_content"
android:layout_width="match_parent">
All subview elements here...
</ScrollView>
</RelativeLayout>
This is the result:
As you can see, the ToolBar extends over the StatusBar and hardware buttons. I don't know if I am approaching this correctly. Am I missing something?
EDIT
This is what the same view look likes when I remove
getDialog().getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
For anyone who's still having this problem, do the following. This just solves half of the problem that is posted i.e. black status bar.
Add following theme to res/value-v21/style
<style name="DialogTheme" parent="#style/Base.Theme.AppCompat.Light.Dialog">
<item name="android:windowTranslucentStatus">true</item>
</style>
And then apply Style on DialogFragment in onCreate
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setStyle(DialogFragment.STYLE_NO_TITLE, R.style.DialogTheme);
}
Edit
if you've problem with your dialog theme then use this style e.g. colorAccent or colorControlHighlight etc
<style name="DialogTheme" parent="#style/ThemeOverlay.AppCompat.Dialog">
<item name="android:windowTranslucentStatus">true</item>
</style>
In my case SYSTEM_UI_FLAG_LAYOUT_STABLE solved problem with overlapping
int width = ViewGroup.LayoutParams.MATCH_PARENT;
int height = ViewGroup.LayoutParams.MATCH_PARENT;
dialog.getWindow().setLayout(width,height);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
dialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
dialog.getWindow().setStatusBarColor(getResources().getColor(R.color.darkGrayTransp));
dialog.getWindow().getDecorView().setSystemUiVisibility(SYSTEM_UI_FLAG_LAYOUT_STABLE);//solves issue with statusbar
dialog.getWindow().setGravity(Gravity.CENTER_HORIZONTAL| Gravity.TOP);
}
Try use the same Style from your App. I tested with simple dialog without fragment and works fine.
Like that:
new Dialog(context, R.style.CardDetailsDialogStyle);
You have to set fitsystemwindows = true. Other way is to add a Space with 0dp and change its height to 25dp when the dialog is going to show.
To change the space size, use layout params, check this post: How to create a RelativeLayout programmatically with two buttons one on top of the other?
<style name="DialogTheme" parent="Theme.AppCompat.Light.NoActionBar">
<item name="android:windowTranslucentStatus">true</item>
<item name="android:windowNoTitle">true</item>
<item name="android:windowFullscreen">true</item>
<item name="android:windowIsFloating">false</item>
</style>
Just apply android:fitsSystemWindows="true" to your root ViewGroup:
`<FrameLayout
android:fitsSystemWindows="true">
<View .../>

Set style programmatically does not work?

This is the code of a compound view I wrote. It uses android.support.v7.widget.CardView as parent class:
public class ItemListItem extends CardView {
TextView tvName;
ImageView ivIcon;
public ItemListItem(Context context) {
super(context, null, R.style.GreenCardView);
LayoutInflater.from(context).inflate(R.layout.item_list_item, this, true);
tvName = (TextView) findViewById(R.id.tvName);
ivIcon = (ImageView) findViewById(R.id.ivIcon);
}
public void setItem(Item item)
{
tvName.setText(item.getName());
}
}
Although I'm adding a custom style (R.style.GreenCardView) to the super constructor call at line 7, it initializes every instance of this class with the default white style. Why is this the case?
edit:
style
<style name="GreenCardView" parent="CardView.Dark">
<item name="contentPadding">#dimen/default_margin</item>
<item name="cardBackgroundColor">#color/guiColor</item>
<item name="cardElevation">#dimen/cardElevation</item>
<item name="cardCornerRadius">#dimen/cardCornerRadius</item>
<item name="android:foreground">?android:attr/selectableItemBackground</item>
</style>
The third argument to the View constructor needs to be a theme attribute, e.g. R.attr.myCardViewStyle. You will need to specify the value of the attribute in your app theme and define the attribute in attrs.xml.
res/values/attrs.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
...
<attr name="myCardViewStyle" format="reference" />
</resources>
res/values/themes.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
...
<style name="AppTheme" parent="...">
...
<item name="myCardViewStyle">#style/GreenCardView</item>
</style>
</resources>

Navigation Drawer item background colour for selected item

I used Android Studio to implement the Navigation Drawer and I can't get the blue colour that is used to show which section we're currently in to change.
I've tried numerous things, I'm currently using a listSelector which looks like:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_activated="true" android:drawable="#color/selected" />
<item android:state_pressed="true" android:drawable="#color/highlight" />
</selector>
I've also tried state_checked. state_pressed works in this situation but the currently selected item is still blue.
EDIT:
I've been examining this more and when the adapter is created the context that is passed is getActionBar().getThemedContext() so I'm thinking if I can find the right attribute to assign to my actionbar style I can change it from there. I've tried a few different attributes with no luck. Does anyone know the exact attribute?
I've also realised if I put
<item name="android:activatedBackgroundIndicator">#drawable/nav_listview_selector</item>
in the main part of my theme and change getActionBar().getThemedContext() for getActivity.getBaseContext then I can change the color but I don't think this is the correct way. I think the themed context should be used. So if anyone knows where the activatedBackgroundIndicator could be put so that it would be used in getActionBar.getThemedContext()
EDIT2:
So the text view used for the listview is one within the SDK it looks like this:
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/text1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceListItemSmall"
android:gravity="center_vertical"
android:paddingStart="?android:attr/listPreferredItemPaddingStart"
android:paddingEnd="?android:attr/listPreferredItemPaddingEnd"
android:background="?android:attr/activatedBackgroundIndicator"
android:minHeight="?android:attr/listPreferredItemHeightSmall"
/>
So I tried modifying the "?android:attr/activatedBackgroundIndicator" at the theme level but it has no effect for checked/selected/activated but it does for pressed. Does anyone know why this is? And how I can change it?
To solve this problem:
1- You don't need android:listSelector under your ListView.
2- Open (or Create) styles.xml under (res/values).
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="android:activatedBackgroundIndicator">#drawable/drawer_list_selector</item>
</style>
3- Under res/drawable folder create drawer_list_selector.xml file
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="#drawable/light_gray_color" />
<item android:state_activated="true" android:drawable="#drawable/red_color" />
<item android:drawable="#android:color/transparent" />
</selector>
4- Under res/drawable create red_color.xml / light_gray_color.xml (or any other name) and add your desired Hex color:
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#C8FF0000"/>
</shape>
5- Open your project AndroidManifest.xml and add android:theme tag (if not exist)
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
Reference / Credit: Changing Navigation Drawer Selected Item Color from default blue
To change the "Navigation Drawer item background colour for selected item" you could do it with the attribut:
colorControlHighlight
In your "styles.xml" it could look like this:
<style name="YourStyleNameFor.NavigationDrawer" parent="ThemeOverlay.AppCompat.Light">
<item name="colorControlHighlight">#color/your_highlight_color</item>
</style>
Don't forget to apply your Style in the tag:
android.support.design.widget.NavigationView
For example in your activity_main.xml it could look like this:
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/navigationdrawer_header"
<!-- the following line referes to your style -->
app:theme="#style/YourThemeNameFor.NavigationDrawer"
<!-- the following two lines are maybe also interesting for you -->
app:itemIconTint="#color/gray3"
app:itemTextColor="#color/gray3"
app:menu="#menu/navigationdrawer_main" />
This is working for me:
First define a drawable item_bg.xml as:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true" android:drawable="#drawable/nav_menu_bg" />
</selector>
Then use this drawable in navigation_main_layout.xml as:
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:itemBackground="#drawable/item_bg"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_navigation"
app:menu="#menu/navigation_main_layout_drawer" />
here is how i have done and it is working, the brief concept is maintain the position of selected item in adapter and call notifyDataSetChanged on calling notifyDatasetChanged the getView method is called again and in get view check the position on the selected position change the background view. Here is the code :
Adapter of NavigationDrawer List View
public class MenuAdapter extends BaseAdapter {
private static final int TYPE_HEADER = 0;
private static final int TYPE_ITEM = 1;
private Context mContext;
private String name;
private int profile;
private int mIcons[];
private int selectedPosition = 0;
private String mNavTitles[];
private LayoutInflater mInflater;
public MenuAdapter(String titles[], int icon[], String Name, int profile) {
mNavTitles = titles;
mIcons = icon;
name = Name;
this.profile = profile;
}
public MenuAdapter(String Titles[], int Icons[], Context mContext) {
mNavTitles = Titles;
mIcons = Icons;
this.mContext = mContext;
mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return mNavTitles.length;
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = mInflater.inflate(R.layout.item_row, parent, false);
TextView textView = (TextView) convertView.findViewById(R.id.rowText);
ImageView imageView = (ImageView) convertView.findViewById(R.id.rowIcon);
final LinearLayout layout = (LinearLayout) convertView.findViewById(R.id.outerLayout);
imageView.setImageResource(mIcons[position]);
textView.setText(mNavTitles[position]);
if (position == selectedPosition)
layout.setBackgroundColor(mContext.getResources().getColor(R.color.app_bg));
else
layout.setBackgroundColor(mContext.getResources().getColor(R.color.normal_bg));
return convertView;
}
public void setSelectedPosition(int position) {
this.selectedPosition = position;
}
}
in your activity do this
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView parent, View view, int position, long id) {
mMenuAdapter.setSelectedPosition(position - 1);
mMenuAdapter.notifyDataSetChanged();
}
}
if anyone still face any difficulty, feel free to ask.
I have implement drawer menu with custom adapter class. May be it will help someone Drawer List
<ListView
android:id="#+id/listview_drawer"
android:layout_width="260dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#color/menu_item_color"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:fadingEdge="none"
/>
drawer_list_item.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/menu_selector"
>
<ImageView
android:id="#+id/imgIcon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="12dp"
android:layout_marginRight="12dp"
android:src="#drawable/ic_menu_home" />
<TextView
android:id="#+id/lblName"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_centerVertical="true"
android:gravity="center_vertical"
android:layout_toRightOf="#+id/imgIcon"
android:minHeight="48dp"
android:textColor="#color/menu_txt_color" />
menu_selector.xml
<selector xmlns:android="http://schemas.android.com/apk/res/android" android:exitFadeDuration="#android:integer/config_mediumAnimTime">
<!-- selected -->
<item android:drawable="#color/menu_item_active_color" android:state_focused="true" android:state_pressed="false"/>
<item android:drawable="#color/menu_item_active_color" android:state_pressed="true"/>
<item android:drawable="#color/menu_item_active_color" android:state_activated="true"/>
<item android:drawable="#color/menu_item_active_color" android:state_checked="true"/>
<item android:drawable="#color/menu_item_active_color" android:state_selected="true"/>
<item android:drawable="#color/menu_item_color" android:state_activated="false"/>
Add this on item click listner of listview
yourlistview.setItemChecked(position, true);
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#color/list_item_back_pressed" android:state_pressed="true" />
<item android:state_activated="true"><color android:color="#color/primary_blue"/></item>
<item android:drawable="#color/list_item_back_normal"/>
</selector>
In addition to providing a custom selector drawable for the listSelector, you should also set the background resource of the list item to a similar selector drawable that has different drawables for the different states.
I usually use my custom adapter that has an int selection field, and a setSelection(int) function. And in the getView function I set the background of the view according to position == selection.
Still not sure why it is that it doesn't work. But the way I found around it is to use my own simple_list_item_activated layout to be passed to the ArrayAdapter which was basically the same except for setting the text colour to white. I then replaced getActionBar().getThemedContext() with getActivity().getBaseContext() and it now has an effect.
This may not be the correct way and may have repercussions in the future, but for now I have it working the way I want it to.
I know its too late but I have solved this issue in my app.
Pls dont think it is silly, just simply change the position of "state_pressed" to top.
<item android:drawable="#drawable/list_item_bg_pressed" android:state_pressed="true"/>
<item android:drawable="#drawable/list_item_bg_normal" android:state_activated="false"/>
<item android:drawable="#drawable/list_item_bg_selected" android:state_activated="true"/>
In Future if anyone comes here using, Navigation Drawer Activity (provided by Studio in Activity Prompt window)
The answer is -
Use this before OnCreate() in MainActivity
int[][] state = new int[][] {
new int[] {android.R.attr.state_checked}, // checked
new int[] {-android.R.attr.state_checked}
};
int[] color = new int[] {
Color.rgb(255,46,84),
(Color.BLACK)
};
ColorStateList csl = new ColorStateList(state, color);
int[][] state2 = new int[][] {
new int[] {android.R.attr.state_checked}, // checked
new int[] {-android.R.attr.state_checked}
};
int[] color2 = new int[] {
Color.rgb(255,46,84),
(Color.GRAY)
};
ColorStateList csl2 = new ColorStateList(state2, color2);
and use this in onNavigationItemSelected() in MainActivity (you dont need to Write this function if you use Navigation Drawer activity, it will be added in MainActivity).
NavigationView nav = (NavigationView) findViewById(R.id.nav_view);
nav.setItemTextColor(csl);
nav.setItemIconTintList(csl2);
nav.setItemBackgroundResource(R.color.white);
Tip - add this code before If else Condition in onNavigationItemSelected()
This worked for me :
implemented menu drawer not by populating the navigation view with list, but with menu items.
created a drawable like this :
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#color/drawer_menu_selector_color" android:state_checked="true"></item>
<item android:drawable="#color/drawer_menu_selector_color" android:state_activated="true"></item>
and in onCreate method , set the id of the menu item which corresponds to selected activity as checked.
and implement the drawable selector file to your navigation drawer like this
app:itemBackground="#drawable/drawer_menu_selector"
fyi : need to define your 'app' namespace.
I searched for solution on this issue, tried everything, and only this solution worked for me.
You can find it on this link https://tuchangwei.github.io/2016/07/18/The-solution-that-the-menu-item-of-Navigation-View-can-t-change-its-background-When-it-is-selected-checked/
All the credit to https://tuchangwei.github.io/

Different backgrounds in one Activity

In Android, is it possible to properly have different background color for the views, the empty space and the action bar?
For example I have a PreferenceScreen in a PreferenceFragment. I have these codes:
Style XML:
<resources xmlns:android="http://schemas.android.com/apk/res/android">
<style name="MyTheme" parent="android:Theme.Holo">
<item name="android:textColor">#color/blue1</item>
<item name="android:background">#color/bg</item>
<item name="android:actionBarStyle">#style/MyActionBar</item>
<item name="android:titleTextStyle">#style/MyActionBar</item>
</style>
<style name="MyActionBar" parent="#android:style/Widget.Holo.ActionBar.Solid">
<item name="android:background">#color/brown1</item>
<item name="android:windowBackground">#color/brown1</item>
</style>
</resources>
my PreferenceFragment class: this already looks like a hack!
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v=super.onCreateView(inflater, container, savedInstanceState);
((ListView) v.findViewById(android.R.id.list)).setBackgroundColor(getResources().getColor(R.color.blue1));
return v;
}
This already makes the ListView items have bg background color, and the empty space after them blue1 background color (note that I had to set them in the opposite way to make this work!), and the ActionBar has brown1 background but the text on it does not and that's really ugly! Also, what the heck does windowBackground do anyway?
EDIT: I've been able to change the background of the title with this hack:
int actionBarTitleId = Resources.getSystem().getIdentifier("action_bar_title", "id", "android");
if (actionBarTitleId > 0) {
TextView title = (TextView) findViewById(actionBarTitleId);
if (title != null)
title.setBackgroundColor(getResources().getColor(R.color.brown1));
}
Now how do I do this for the logo and the "Up" arrow to the left of the logo?
The solution is to remove the titleTextStyle from the style XML.

Categories

Resources