setBackgroundResource doesn't work - java

Well, I'm trying to change my drawer navigator whenever I change the fragment, I managed to change the ActionBar color and the Background color, but the thing is that with the Background is not enough... I saw that I declare a BackgroundResource with other colors, and when I try to change the color it does not work.
My MainActivity.xml
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- Displaying Fragments -->
<FrameLayout
android:id="#+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<!-- Displaying Drawer -->
<ListView
android:id="#+id/list_slidermenu"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#color/list_divider"
android:dividerHeight="1dp"
android:listSelector="#drawable/drawer_list_selection"
android:background="#color/list_background"/>
</android.support.v4.widget.DrawerLayout>
My colors.xml (I've tried to change it manually but I don't know how to do, then I've created as colors as items are on my drawable navigator).
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="list_item_title">#fff</color>
<color name="list_background">#458A79</color>
<color name="list_background2">#ffc591</color>
<color name="list_background3">#ab91ff</color>
<color name="list_background4">#f784fe</color>
<color name="list_background5">#91dfff</color>
<color name="list_background_pressed">#6FA698</color>
<color name="list_background_pressed2">#ffc591</color>
<color name="list_background_pressed3">#ab91ff</color>
<color name="list_background_pressed4">#f784fe</color>
<color name="list_background_pressed5">#91dfff</color>
<color name="list_divider">#fff</color>
<color name="counter_text_bg">#626262</color>
<color name="counter_text_color">#c5c4c4</color>
</resources>
And the thing that I've tried on my MainActivity.java is
private void displayView(int position) {
// update the main content with called Fragment
Fragment fragment = null;
LlistaGenericaFragment frag = null;
FragmentTransaction ft = null;
ActionBar bar = getActionBar();
bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#256F5C")));
switch (position) {
case 0:
fragment = new MetallsAlcalinsFragment();
bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#ffc591")));
mDrawerList.setBackground(new ColorDrawable(Color.parseColor("#ffc591"))); //set the background but not the ListView
mDrawerList.setBackgroundResource(R.color.list_background2); //Don't see any change
break;
I know I'm doing something wrong, but I don't get what... Could you explain me how can I change this each time I change the fragment?

What you would want to do then is create a drawable selector -> list_selector.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#color/list_background2" android:state_pressed="true"/>
<item android:drawable="#color/list_background" />
</selector>
then on your list add this as a selector:
mDrawerList.setSelector(R.drawable.list_selector);
If you want to do this every time something happens in your fragment, you would create an interface:
public iterface TalkToActivity(){
public void sendChangeEvent(int changeType);
}
in Your fragment create a local variable:
TalkToActivity m_callBack;
Then in your onAttach method of the fragment:
#Override
public void onAttach(Activity activity) {
// Call to the Super Class
super.onAttach(activity);
// Attempt to Add the Interface
try {
m_callBack = (TalkToActivity) activity;
} catch (ClassCastException e) {
// Print to LogCat if the Parent Did not implement the interface
Log.e(FRAGMENT_TAG, "Failed to implement interface in parent.", e);
}
}
and then in the event that you want to capture and communicate the change:
public void buttonWasPressed(int changeType){
if(m_callBack != null){
m_callBack.sendChangeEvent(changeType);
}
}
Finally, in your activity make your activity 'implents TalkToActivity' which will force you to override the method sendChangeEvent and in this method
#Override
public void sendChangeEvent(int changeType){
switch(changeType){
case 0:
// Update you UI like above
// ...
if(mDrawerList != null){
mDrawerList.setSelector(R.drawable.list_selector);
}
break;
default: break;
}
}
NOTE: If you have list_item.xml and an adapter:
<?xml version="1.0" encoding="utf-8" ?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/linearLayoutItem"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/textViewNavItem"
android:layout_height="wrap_content"
android:layout_width="match_parent"/>
</LinearLayout
Then get a reference to the parent item
LinearLayout linearlayoutItem = (LinearLayout) findViewById(R.id.linearLayoutItem);
and dynamically change the background of this with the above approach...
linearLayoutItem.setBackground(R.drawable.list_selector);
but create 6 different list_selector_num1.xml etc... and change this using the switch statement. but you need the adapter to have a method like
public void updateViewBackground(Drawable drawable) {}
which will be in your adapter to do this.
For a demo on this communication between Fragments & activities look at:
https://github.com/lt-tibs1984/InterfaceDemo

Fragments talk to the main activity via bundle and onPause()
Passing data between a fragment and its container activity

Related

Change app theme globally programatically

I am writing an app which has both light and dark modes as declared here:
styles.xml
<style name="Noon" parent="Theme.AppCompat.NoActionBar">
<item name="upper_bg">#drawable/day_sky_top</item>
<item name="lower_bg">#drawable/day_sky</item>
<item name="android:statusBarColor">#color/colorPrimaryDark</item>
</style>
<style name="Night" parent="Theme.AppCompat.NoActionBar">
<item name="upper_bg">#drawable/night_sky_top</item>
<item name="lower_bg">#drawable/night_sky</item>
<item name="android:statusBarColor">#color/colorNightDark</item>
</style>
By following this answer, I created the following file:
/res/values/attrs.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="customAttrs">
<attr name="upper_bg" format="reference" />
<attr name="lower_bg" format="reference" />
</declare-styleable>
</resources>
And customized my ImageViews like this:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:id="#+id/top_bg"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.65"
android:src="?attr/upper_bg"/>
<ImageView
android:id="#+id/bottom_bg"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.35"
android:src="?attr/lower_bg"/>
</LinearLayout>
(Note that this is part of the code, all tags are properly closed.)
Everything works well provided I have:
boolean night = true;
setTheme(night ? R.style.Night : R.style.Noon);
setContentView(R.layout.activity_main); // or whatever activity I'm in.
on every single Activity of my app. Is there a way to run this code ONCE so that my theme changes globally?
You can still add a BaseActivity to then override override fun onCreate(), delegating it the responsibility of setTheme() for any other Activity that inherits from it.
override fun onCreate(savedInstanceState: Bundle?) {
val night = true
setTheme(if (night) R.style.Night else R.style.Noon)
}
if you don't prefer BaseActivity, you can create an extension function somewhere in charged of set theme according user preferences:
fun Activity.setTheme() {
val night = true
// Or even have more than two theme styles
this.setTheme(if (night) R.style.Night else R.style.Noon)
}
To then be called like this:
override fun onCreate(savedInstanceState: Bundle?) {
setTheme()
}
UPDATE: Java code
This class would be your base class for each required Activity
public abstract class BaseActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
boolean night = true;
setTheme(night ? R.style.Night : R.style.Noon);
}
}
So now, imagine you have to implement "Feature 1" and "Feature 2", so that, you just inherits them from BaseActivity.
"Feature 1":
public class Feature1Activity extends BaseActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); // <- BaseActivity's onCreate() will set theme for you
setContentView(R.layout.activity_feature_1);
}
}
"Feature 2":
public class Feature2Activity extends BaseActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); // <- BaseActivity's onCreate() will set theme for you
setContentView(R.layout.activity_feature_2);
}
}
Yes you can !
You have to use method setDefaultNightMode() of class AppCompatDelegate that take the value of the theme you want to apply , the values available is MODE_NIGHT_NO & MODE_NIGHT_YES & MODE_NIGHT_FOLLOW_SYSTEM for light , night and phone default theme respectively , you can do something like this :
AppCompatDelegate.setDefaultNightMode(THE_MODE_YOU_WANT);
Its important to note that starting with AppCompat v1.0.0 , when this method get called it recreates all running activity to apply the theme .
If you are running Api 29 or higher , you should consider using Force Dark , you can check it all in the official document to get better understanding of it .
Enjoy !

How to Change the background color of Spinner selection in Android

In the above picture GAIN 3 is selected but its not visible properly , so how can i change that color to darker color.
basically i want to change the selected text background in darker color.
I'm using com.jaredrummler.materialspinner.MaterialSpinner Spinner.
Here's the java implementation.
spinner.setOnItemSelectedListener(new MaterialSpinner.OnItemSelectedListener<String>() {
#Override public void onItemSelected(MaterialSpinner view, int position, long id, String item) {
text = spinner.getText().toString();
Log.e("Spinner Listener",text);
if(text.contains("GAIN 0")){
sendToDevice("F");
} else if(text.contains("GAIN 1")){
sendToDevice("G");
} else if(text.contains("GAIN 2")){
sendToDevice("H");
} else if(text.contains("GAIN 3")){
sendToDevice("I");
}
}
});
And the layout item looks like the following.
<com.jaredrummler.materialspinner.MaterialSpinner
android:id="#+id/spinner"
app:ms_dropdown_max_height="350dp"
app:ms_dropdown_height="wrap_content"
android:textColorHighlight="#000000"
android:layout_width="130dp"
style="#style/spinner_style"
android:popupTheme="#android:style/ThemeOverlay.Material"
android:textColor="#color/blue"
android:layout_below="#+id/testmodetitle"
android:layout_height="wrap_content"
android:layout_marginTop="55dp"
android:layout_alignBaseline="#+id/button1"
android:layout_alignBottom="#+id/button1"
android:layout_toEndOf="#+id/button1"
android:layout_marginStart="30dp" />
To change background color and other color this library has provided some attributes. To change background color of selected item use below code.
<com.jaredrummler.materialspinner.MaterialSpinner
android:id="#+id/spinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:ms_background_selector="#drawable/selector_gray_white_spinner"
app:ms_dropdown_height="wrap_content"
app:ms_dropdown_max_height="350dp" />
create one selector in drawable having name selector_gray_white_spinner.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="true" android:state_pressed="true" android:drawable="#color/darkGray"/>
<item android:state_focused="false" android:state_pressed="true" android:drawable="#color/darkGray"/>
<item android:state_focused="true" android:drawable="#android:color/white"/>
<item android:state_focused="false" android:state_pressed="false" android:drawable="#android:color/white"/>
</selector>
Add dark color in your color.xml file
<color name="darkGray">#acacac</color>
Use this way it will help you:
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, list) {
#Override
public View getDropDownView(int position, View convertView, ViewGroup parent)
{
View v = null;
v = super.getDropDownView(position, null, parent);
// If this is the selected item position
if (position == selectedItem) {
v.setBackgroundColor(Color.BLUE);
}
else {
// for other views
v.setBackgroundColor(Color.WHITE);
}
return v;
}
};
There are some attributes available along with the implementation of that specific library. Please have a look in the readme.md section where the attributes are listed.
I think you might consider using ms_background_selector attribute in your layout where you have declared the spinner.
So the layout declaration will look like this.
<com.jaredrummler.materialspinner.MaterialSpinner
android:id="#+id/spinner"
app:ms_background_selector="#drawable/your_darker_selector"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
Add a file named your_darker_selector.xml and put the following code inside the file.
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true" android:drawable="#android:color/darker_gray"/>
<item android:state_checked="false" android:drawable="#android:color/white" />
</selector>
Modify the color from the selector file as per your necessity.
Give html colour code for the first item of spinner.
String styledText = "This is <font color='red'>simple</font>.";
textView.setText(Html.fromHtml(styledText),
TextView.BufferType.SPANNABLE);

How to set an item in a ListView from within a Navigational Drawer as selected? [duplicate]

I have two fragments. The first with buttons inside, the other with a ListView inside (ListFragment).
I would like the first fragment (thanks to its buttons) to allow the user to browse the ListView which is in the second fragment.
So I want the ListView to be controlled by the first fragment with buttons.
I've no problem communicating between fragment (sending orders from 1st fragment to the 2nd), but I don't know how to tell my ListView to select (programmatically) a particular list item.
What kind of ListView should I use and how can I tell the ListView to Select/Highlight/Focus one of its items?
I am in touch mode as the user presses on the buttons of the 1st fragment.
Should I use setFocusableInTouchMode(true) or setChoiceMode(ListView.CHOICE_MODE_SINGLE) or something else?
This is for everyone trying to :
-Select programmatically an Item in a ListView
-Making this Item stay Highlighted
I'm working on Android ICS, I don't know if it works for all levels Api.
First create a listview (or get it if you're already in a listActivity/listFragment)
Then set the choice mode of your listview to single with :Mylistview.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
Then select programmatically your item with :Mylistview.setItemChecked(position, true); (position being an integer indicating the rank of the item to select)
Now your item is actually selected but you might see absolutely nothing because there's no visual feedback of the selection. Now you have two option : you can either use a prebuilt listview or your custom listview.
1) If you want a prebuilt listview, give a try to simple_list_item_activated_1, simple_list_item_checked , simple_list_item_single_choice, etc...
You can set up your listview like this for e.g : setListAdapter(new ArrayAdapter<String>(this, R.layout.simple_list_item_activated_1, data))
following which prebuilt listview you chose you'll see now that when selected you have a checkbox ticked or the backgound color changed , etc...
2) If you use a custom listview then you'll define a custom layout that will be used in each item. In this XML layout you will attribute a selector for each part view in you row which need to be changed when selected.
Let's say that when selected you want your row to change the color of the text and the color of the background. Your XML layout can be written like :
<?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:background="#drawable/menu_item_background_selector"
android:orientation="horizontal" >
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:textColor="#drawable/menu_item_text_selector" />
Now, in the drawable folder you create menu_item_background_selector.xml and menu_item_text_selector.xml.
menu_item_text_selector.xml :
<?xml version="1.0" encoding="utf-8"?>
<selector
xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_activated="true"
android:color="#FFF">
</item>
<item android:state_pressed="true"
android:color="#FFF">
</item>
<item android:state_pressed="false"
android:color="#000">
</item>
</selector>
The text will be white when selected.
Then do something similar for your background: (remember that you're not forced to use color but you can also use drawables)
menu_item_background_selector.xml :
<?xml version="1.0" encoding="utf-8"?>
<selector
xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_activated="true"
android:color="#0094CE">
</item>
<item android:state_pressed="true"
android:color="#0094CE">
</item>
<item android:state_pressed="false"
android:color="#ACD52B">
</item>
</selector>
Here the background is blue when selected and green when it is not selected.
The main element I was missing was android:state_activated. There's indeed (too) many states : activated,pressed,focused,checked,selected...
I'm not sure if the exemple I gave with android:state_activated and android:state_pressed is the best and cleanest one but it seems to work for me.
But I didn't need to make my own class in order to get a Custom CheckableRelativeLayout (which was dirty and scary) nor I used CheckableTextViews. I don't know whyothers used such methods, it maybe depends on the Api level.
Try AbsListView.performItemClick(...)
See this post on how to use performItemClick.
This is what worked for me:
1) Set the choice behavior for the List.
mListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
2) Sets the checked state of the specified position.
mListView.setItemChecked(1,true); //Don't make the same mistake I did by calling this function before setting the listview adapter.
3) Add a new style inside the style resource (res/values) like this:
<style name="activated" parent="android:Theme.Holo">
<item name="android:background">#android:color/holo_green_light</item>
</style>
Feel free to use whichever colours you like.
4) Use the previously defined style in your ListView:
<ListView
android:id="#+id/listview"
style="#style/activated"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"/>
Or in the layout you use as row.
<?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"
style="#style/activated"
>
<!--widgets for your row here-->
</LinearLayout>
Hope that helps anyone!
Try mListView.setSelection(position);
Jecimi's answer worked for me except for small part. I would like to share it for others. Calling list.setItemChecked( 0, true ); in onCreate() of FragmentActivity did not work. In getView() of adapter list.getCheckedItemPosition( ) returned -1.
I have to call this method from protected void onPostCreate( Bundle savedInstanceState ).
You can use ListView#setSelection(int)
package com.example.samsung;
import com.example.samsung.*;
import com.example.samsung.R;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;
public class Firstscreen extends Activity implements OnItemSelectedListener {
Button btn;
Spinner sp;
public String[] product = { "ML-1676P/XIP","SLM2021W/XIP","SL-M2826ND/XIP","SL-M2826ND/XIP","SL-M2826ND/XIP","SL-M3320ND/XIP","SL-M3820ND/XIP","SL-M4020ND/XIP"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_firstscreen);
btn = (Button) findViewById(R.id.bn);
sp= (Spinner) findViewById(R.id.sp);
}
public void button (View v){
{
Intent i = new Intent(Firstscreen.this,ML1676P.class);
startActivity(i);
}
Spinner s1 = (Spinner) findViewById(R.id.sp);
ArrayAdapter<String> adapter
= new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, product); // find other layout parameters
s1.setAdapter(adapter);
s1.setOnItemSelectedListener(new OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
private Object product() {
// TODO Auto-generated method stub
return null;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.firstscreen, menu);
return true;
}
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
<LinearLayout 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=".Firstscreen"
android:orientation="vertical" >
<TextView
android:id="#+id/tv1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#FF35B5E5"
android:layout_centerInParent="true"
android:text="CHOOSE THE PRODUCT FROM THE LIST" />
<Spinner
android:id="#+id/sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:drawSelectorOnTop="true" />
<Button
android:id="#+id/bn"
android:layout_width="285dp"
android:layout_height="wrap_content"
android:text=" GO "
android:onClick="button"/>
</LinearLayout>
select an item in a listview it should go to the specific selected item page when button is clicked how to do it.The code is snippet above
I do like this:
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
try {
int pos = 0;
listview.performItemClick(null, pos, listview.getItemIdAtPosition(pos) );
} catch (Exception e) {
e.printStackTrace();
}
}
}
Just add the following line to the layout of your custom listview:
android:background="?android:attr/activatedBackgroundIndicator"
For a full working example see:
https://elimelec#bitbucket.org/elimelec/custombaseadapter.git

How to Set Icon to display on the far right in Java

getSupportActionBar().setLogo(R.drawable.addicon);
The code above seems to place my Icon in the Centre . I would like to place to the far right and make it clickable as well . At the moment it the image for the icon is in the project files as a drawable I have not included it in any xml files.
You can set android:layoutDirection="rtl" in your toolbar xml for place it to right and
set below code for clickable :
getSupportActionbar().setDisplayHomeAsUpEnabled(true);
and :
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
//Do stuff
return true;
default:
return super.onOptionsItemSelected(item);
}
}
There are 2 approaches for doing that.
Option Menus
Creating custom toolbar.
With Option Menus
create main.xml under res/menu.
<menu 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"
tools:context="com.ioa.MainActivity" >
<item
android:id="#+id/action_addition"
android:icon="#drawable/addicon"
android:orderInCategory="100"
android:title="Addition"
app:showAsAction="always"/>
</menu>
and inside your activity create menu like,
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
you can perform Action on particular menu item.
#Override
public boolean onOptionsItemSelected(MenuItem Item) {
if (Item.getItemId() == R.id.action_addition) {
// perform action
}
return super.onOptionsItemSelected(paramMenuItem);
}
With custom toolbar
Create your ToolBar like this,
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/ColorPrimary"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<ImageView
android:id="#+id/add"
android:layout_width="46dp"
android:layout_height="46dp"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="4dp"
android:clickable="true"
android:src="#drawable/ic_launcher" />
</RelativeLayout>
</android.support.v7.widget.Toolbar>
and now you can perform click event of particular ImageView.
ImageView add = (ImageView) findViewById(R.id.add);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// do work.
}
});
happy Coding.
You Need 3 Things:
A Custom Toolbar Layout
Include the toolbar in your activity
Set the Logo to the toolbar
Create new Resource Layout:
include_toolbar.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:background="?attr/colorPrimaryDark"
android:id="#+id/include_toolbar"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar" />
Change Your Activity File: MainActivity.java
public class BaseActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Toolbar toolbar = (Toolbar)findViewById(R.id.include_toolbar);
setSupportActionBar(toolbar);
toolbar.setNavigationIcon(R.mipmap_ic_launcher);
}
}
And here's the styles.xml:
<!-- language: xml-->
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="colorPrimary">#3F51B5</color>
</resources>

Custom adapter, selected item background

I have a problem whith custom adapter view.
I try, change background of view on Click event.
I have AdapterView.OnItemClickListener, where i get selected item, and calling myListView.invalidate();
After invalidate, calling adapters getView(...). Here code for this:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ProjectAdapterData projectItem;
if (row == null) {
LayoutInflater inflater = LayoutInflater.from(context);
row = inflater.inflate(R.layout.project_small_item_layout, null);
ProjectAdapterData projectAdapterData = new ProjectAdapterData();
row.setTag(projectAdapterData);
name = (TextView)row.findViewById(R.id.txtObjectName);
if (objectData[position].Name!= null)
name.setText(objectData[position].Name);
adress = (TextView)row.findViewById(R.id.txtObjectAdress);
if (objectData[position].Adress != null)
adress.setText(objectData[position].Adress);
}
else {
background = (RelativeLayout)row.findViewById(R.id.rlProjectBackground);
if (objectData[position].isSelected)
background.setBackgroundColor(context.getResources().getColor(R.color.cProjectSelected));
else
background.setBackgroundResource(R.color.cProjectUnSelected); //it's calls, but no result
row.invalidate();
}
return row;
}
My question, why background doesn't change?
My selector_list
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_selected="true"
android:color="#color/cProjectSelected"/>
<item android:state_selected="false"
android:color="#color/cProjectUnSelected"/>
</selector>
you can use selector to highlight item
In drawable folder create a xml file
list_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" android:exitFadeDuration="#android:integer/config_mediumAnimTime">
<item android:drawable="#color/blue" android:state_activated="true"/>
<item android:drawable="#color/blue" android:state_selected="true"/>
<item android:drawable="#color/transparent"/>
</selector>
and set listSelector in xml for your listview like
android:listSelector="#drawable/list_selector"
color.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="BLACK">#000000</color>
<color name="WHITE">#FFFFFF</color>
<color name="light_grey">#a5acb0</color>
<color name="brown">#525964</color>
<color name="dark_grey">#212121</color>
<color name="aqua">#a6b1ba</color>
<color name="red_cherry">#C9282D</color>
<color name="silver">#A9A9A9</color>
<color name="black">#000000</color>
<color name="transparent">#00000000</color>
<color name="white">#FFFFFF</color>
<color name="blue">#00aceb</color>
<color name="spiritclips_bck">#8AB8E0</color>
<color name="translucent_black">#55000000</color>
<color name="grid_bck">#627583</color>
<color name="grey">#393430</color>
<color name="dark_grey_bg">#1f1c17</color>
<color name="login_font_color_1">#546778</color>
<color name="login_font_color_2">#8E8E8E</color>
<color name="blue_txt">#0f5690</color>
</resources>
for custom_list_item the layout should be
<?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"
android:background="?android:attr/activatedBackgroundIndicator" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:textStyle="bold" />
</LinearLayout>
and minimum version of your application should be 11

Categories