How to highlight the imagebutton when it is pressed - android

I want my imagebutton to hightlight it self, as the normal glow effect when a "normal" button is pressed. So i tried to put the image in, but then there is a "gray field" in the back of the image so i made it transparent so only the image will show but then the glow effect disappeared. Is there a solution to this? :)
please see imgur image as a example- Example image here
if it is to "hard" I can live with the gray field behind the image but is it possible then to make it green with the same highlight effect?
Should i put the code in MainActivity or my fragment java?
Fragment java
public class FirstFragment extends Fragment {
private View view ;
public FirstFragment(){
}
Button sendSMS;
Button sendSMSaon;
Button sendSMSaoff;
Button sendSMSrela1;
Button sendSMSrela2;
EditText msgTxt;
EditText aonTxt;
EditText aoffTxt;
EditText rela1txt;
EditText rela2txt;
Button taframnummer;
TextView nyanumtxt;
//TextView nya;
//TextView nsp;
TextView tstnr;
#SuppressWarnings("ResourceType")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.first_layout, container, false);
return inflater.inflate(R.layout.first_layout, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
view = getActivity().findViewById(R.id.content_frame);
nyanumtxt = (TextView) getActivity().findViewById(R.id.raderanumtxt);
sendSMS = (Button)view.findViewById(R.id.skicka);
sendSMSaon = (Button)view.findViewById(R.id.skickaaon);
sendSMSaoff = (Button)view.findViewById(R.id.skickaaoff);
sendSMSrela1 = (Button)view.findViewById(R.id.skickarela1);
sendSMSrela2 = (Button)view.findViewById(R.id.skickarela2);
msgTxt = (EditText)view.findViewById(R.id.Textmeddelande);
aonTxt = (EditText)view.findViewById(R.id.aon);
aoffTxt = (EditText)view.findViewById(R.id.aoff);
rela1txt = (EditText)view.findViewById(R.id.rela1txt);
rela2txt = (EditText)view.findViewById(R.id.relä2txt);
taframnummer = (Button) view.findViewById(R.id.taframnummer);
//nsp = (TextView) view.findViewById(R.id.nummertestsp);
// tstnr = (TextView) view.findViewById(R.id.numretladd);
// view = getActivity().findViewById(R.id.content_frame);
taframnummer.setVisibility(INVISIBLE);
msgTxt.setVisibility(INVISIBLE);
aonTxt.setVisibility(INVISIBLE);
aoffTxt.setVisibility(INVISIBLE);
rela1txt.setVisibility(INVISIBLE);
rela2txt.setVisibility(INVISIBLE);
sendSMSaoff.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String mymsgaoff = aoffTxt.getText().toString();
String theNumberr = nyanumtxt.getText().toString();
sendMsg(theNumberr, mymsgaoff);
}
}
);
sendSMSaon.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String mymsgaon = aonTxt.getText().toString();
String theNumberr = nyanumtxt.getText().toString();
sendMsg(theNumberr, mymsgaon);
}
}
);
sendSMS.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String myMsg = msgTxt.getText().toString();
String theNumberr = nyanumtxt.getText().toString();
sendMsg(theNumberr, myMsg);
}
}
);
sendSMSrela1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String myMsgrela1 = rela1txt.getText().toString();
String theNumberr = nyanumtxt.getText().toString();
sendMsg(theNumberr, myMsgrela1);
}
}
);
sendSMSrela2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String mymsgrela2 = rela2txt.getText().toString();
String theNumberr = nyanumtxt.getText().toString();
sendMsg(theNumberr, mymsgrela2);
}
}
);
// return view;
}
private void sendMsg(String theNumber, String myMsg)
{
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(theNumber, null, myMsg, null, null);
}
}
Here my MainActivity
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
//TextView tstnr;
TextView radertst;
Button sendSMSaon;
EditText aonTxt;
//TextView nrladd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
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();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
// tstnr = (TextView) findViewById(R.id.nummertestsp);
radertst = (TextView) findViewById(R.id.raderanumtxt);
sendSMSaon = (Button)findViewById(R.id.skickaaon);
aonTxt = (EditText)findViewById(R.id.aon);
// nrladd = (TextView)findViewById(R.id.numretladd);
}
//This is where the call for the value in the setttings are.
//Här är så att man kan lägga in values från inställningar till mainactivity.
public void displayData(View view){
SharedPreferences prefs =PreferenceManager.getDefaultSharedPreferences(this);
String name = prefs.getString("example_text", "");
radertst.setText(name + " ");
}
//downbelow is where the onresume so the value boots up with the app.
//nedanför är för att appen ska ladda koden i settings direkt när man startar
#Override
protected void onResume() {
super.onResume();
SharedPreferences prefs =PreferenceManager.getDefaultSharedPreferences(this);
String name = prefs.getString("example_text", "");
radertst.setText(name + " ");}
#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) {
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
android.app.FragmentManager fragmentManager = getFragmentManager();
if (id == R.id.nav_first_layout) {
fragmentManager.beginTransaction()
.replace(R.id.content_frame
, new FirstFragment())
.commit();
// Handle the camera action
} else if (id == R.id.nav_second_layout) {
fragmentManager.beginTransaction()
.replace(R.id.content_frame
, new SecondFragment())
.commit();
} else if (id == R.id.nav_third_layout) {
fragmentManager.beginTransaction()
.replace(R.id.content_frame
, new ThirdFragment())
.commit();
}
else if (id == R.id.nav_share) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://hellmertz.se"));
startActivity(browserIntent);
return true;
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}

Put the imageView that you want to highlight above a View with bright color and set the visibility of the view equal to View.GONE. Now with your ImageButton
((ImageButton)findViewById(R.id.myImageBtn)).setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: {
myView.setVisibility(View.VISIBLE);
break;
}
case MotionEvent.ACTION_UP:
myView.setVisibility(View.GONE);
break;
// Your action here on button click
case MotionEvent.ACTION_CANCEL: {
myView.setVisibility(View.GONE);
break;
}
}
return true;
}
});

You can user selector drawable and have 3 different button drawables for each state. Create these file is drawables folder and add this line to button android:background="#drawable/button_selector"
button_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- pressed -->
<item android:drawable="#drawable/camera_button_hold" android:state_pressed="true"/>
<!-- focused -->
<item android:drawable="#drawable/camera_button_hold" android:state_focused="true"/>
<!-- default -->
<item android:drawable="#drawable/camera_button_normal"/>
</selector>
camera_button_hold.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<solid
android:color="#673ab7"/>
</shape>
camera_button_normal.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<stroke
android:width="2dp"
android:color="#673ab7"/>
</shape>

Related

Onclick in fragment, FATAL EXCEPTION. Shared preferences to a fragment

Basic info
I am using the Settings Activity and navigation menu : and i have button to display the data (which is the number) from the settings to a textview. It's a sms app
Problem
I have the textview in context_main (The first screen when you start the app) But i would really like to have the textview in my fragment and when i press the button "the onlick" will display the value from settings.
The Button is in the fragment. and when i click the button it works^^ for the context_main se below code.
public void displayData(View view){
SharedPreferences prefs =PreferenceManager.getDefaultSharedPreferences(this);
String restoredText = prefs.getString("example_text", "");
radertst.setText(restoredText);
}
But when i press a button to send a sms and i linked it with the textfield for where the number is but then i get this.
09-16 20:47:03.501 5389-5389/c.timno.smsgsm20 E/AndroidRuntime: FATAL EXCEPTION: main
Process: c.timno.smsgsm20, PID: 5389
java.lang.NullPointerException
at c.timno.smsgsm20.FirstFragment$1$override.onClick(FirstFragment.java:102)
at c.timno.smsgsm20.FirstFragment$1$override.access$dispatch(FirstFragment.java)
at c.timno.smsgsm20.FirstFragment$1.onClick(FirstFragment.java:0)
at android.view.View.performClick(View.java:4443)
at android.view.View$PerformClick.run(View.java:18475)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:788)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:604)
at dalvik.system.NativeStart.main(Native Method)
This my
MainActivity java class
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
TextView tstnr;
TextView radertst;
EditText nantxt;
Button sendSMSaon;
EditText aonTxt;
TextView nrladd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
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();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
tstnr = (TextView) findViewById(R.id.nummertestsp);
radertst = (TextView) findViewById(R.id.raderanumtxt);
nantxt =(EditText) findViewById(R.id.nummer);
sendSMSaon = (Button)findViewById(R.id.skickaaon);
aonTxt = (EditText)findViewById(R.id.aon);
nrladd = (TextView)findViewById(R.id.numretladd);
}
//This is where the call for the value in the setttings are.
//Här är så att man kan lägga in values från inställningar till mainactivity.
public void displayData(View view){
SharedPreferences prefs =PreferenceManager.getDefaultSharedPreferences(this);
String name = prefs.getString("example_text", "");
radertst.setText(name + " ");
}
//downbelow is where the onresume so the value boots up with the app.
//nedanför är för att appen ska ladda koden i settings direkt när man startar
#Override
protected void onResume() {
super.onResume();
SharedPreferences prefs =PreferenceManager.getDefaultSharedPreferences(this);
String name = prefs.getString("example_text", "");
radertst.setText(name + " ");}
#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) {
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
android.app.FragmentManager fragmentManager = getFragmentManager();
if (id == R.id.nav_first_layout) {
fragmentManager.beginTransaction()
.replace(R.id.content_frame
, new FirstFragment())
.commit();
// Handle the camera action
} else if (id == R.id.nav_second_layout) {
fragmentManager.beginTransaction()
.replace(R.id.content_frame
, new SecondFragment())
.commit();
} else if (id == R.id.nav_third_layout) {
fragmentManager.beginTransaction()
.replace(R.id.content_frame
, new ThirdFragment())
.commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
The fragment java file
public class FirstFragment extends Fragment {
private View view ;
public FirstFragment(){
}
Button sendSMS;
Button sendSMSaon;
Button sendSMSaoff;
Button sendSMSrela1;
Button sendSMSrela2;
EditText msgTxt;
EditText numTxt;
EditText aonTxt;
EditText aoffTxt;
EditText rela1txt;
EditText rela2txt;
Button taframnummer;
TextView nyanumtxt;
TextView ifirt;
TextView tstnr;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.first_layout, container, false);
nyanumtxt = (TextView)view.findViewById(R.id.raderanumtxt);
sendSMS = (Button)view.findViewById(R.id.skicka);
sendSMSaon = (Button)view.findViewById(R.id.skickaaon);
sendSMSaoff = (Button)view.findViewById(R.id.skickaaoff);
sendSMSrela1 = (Button)view.findViewById(R.id.skickarela1);
sendSMSrela2 = (Button)view.findViewById(R.id.skickarela2);
msgTxt = (EditText)view.findViewById(R.id.Textmeddelande);
numTxt = (EditText)view.findViewById(R.id.nummer);
aonTxt = (EditText)view.findViewById(R.id.aon);
aoffTxt = (EditText)view.findViewById(R.id.aoff);
rela1txt = (EditText)view.findViewById(R.id.rela1txt);
rela2txt = (EditText)view.findViewById(R.id.relä2txt);
taframnummer = (Button) view.findViewById(R.id.taframnummer);
tstnr = (TextView) view.findViewById(R.id.numretladd);
msgTxt.setVisibility(View.INVISIBLE);
aonTxt.setVisibility(View.INVISIBLE);
aoffTxt.setVisibility(View.INVISIBLE);
rela1txt.setVisibility(View.INVISIBLE);
rela2txt.setVisibility(View.INVISIBLE);
//testnedan
LayoutInflater lf = getActivity().getLayoutInflater();
view = lf.inflate(R.layout.first_layout, container, false);
//ovantest
sendSMSaoff.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String mymsgaoff = aoffTxt.getText().toString();
String theNumber = numTxt.getText().toString();
sendMsg(theNumber, mymsgaoff);
}
}
);
sendSMSaon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String mymsgaon = aonTxt.getText().toString();
String theNumber = nyanumtxt.getText().toString();
sendMsg(theNumber, mymsgaon);
}
}
);
sendSMS.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String myMsg = msgTxt.getText().toString();
String theNumber = numTxt.getText().toString();
sendMsg(theNumber, myMsg);
}
}
);
sendSMSrela1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String myMsgrela1 = rela1txt.getText().toString();
String theNumber = numTxt.getText().toString();
sendMsg(theNumber, myMsgrela1);
}
}
);
sendSMSrela2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String mymsgrela2 = rela2txt.getText().toString();
String theNumber = numTxt.getText().toString();
sendMsg(theNumber, mymsgrela2);
}
}
);
return view;
}
private void sendMsg(String theNumber, String myMsg)
{
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(theNumber, null, myMsg, null, null);
}
}
if you look at
sendSMSaoff.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String mymsgaoff = aoffTxt.getText().toString();
String theNumber = numTxt.getText().toString();
sendMsg(theNumber, mymsgaoff);
}
The numTxt is where i want the value to be loaded and it's in the first layout xml not context_main. So for some reason it wont be loaded there. Imgur image
If I'm understanding you correctly, R.id.raderanumtxt is in the MainActivity's layout file and not FirstFragment's.
That means that it won't be found in the onCreateView() method of FirstFragment the way you're accessing it. The view object there is the layout you just loaded:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.first_layout, container, false);
nyanumtxt = (TextView)view.findViewById(R.id.raderanumtxt); // <- this assignment won't work
...
}
You're also inflating R.layout.first_layout twice, which is unnecessary.
To get access to a View in the Activity, you can do something like this:
View view = getActivity().findViewById(R.id.viewid);
EDIT:
Without seeing your layouts, I can't be sure, but try and replace:
nyanumtxt = (TextView)view.findViewById(R.id.raderanumtxt);
... with:
nyanumtxt = (TextView) getActivity().findViewById(R.id.raderanumtxt);
That way you're looking for R.id.raderanumtxt in the entire Activity layout. This will only work if the Activity is available and the layout has already been added, so to be safer I'd move this assignment to onViewCreated() instead of onCreateView().

Android Actionbar shows no items

I'm new to android and have this problem for while: No item appear on action bar, as you can see in the image below:
Here is my menu_main.xml:
<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.myappshop.myapp.MainActivity">
<item
android:id="#+id/action_favorite"
android:icon="#drawable/share_icon"
android:title="#string/share"
app:showAsAction="always"/>
<item
android:id="#+id/action_settings"
android:orderInCategory="100"
android:title="#string/action_settings"
app:showAsAction="ifRoom" />
</menu>
And the MainActivity.java:
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
EditText mEditTextWord;
EditText mEditTextDefinition;
DictionaryDatabase mDB;
ListView mListView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDB = new DictionaryDatabase(this);
mEditTextWord = (EditText)findViewById(R.id.editTextWord);
mEditTextDefinition = (EditText)findViewById(R.id.editTextDefinition);
Button buttonAddUpdate = (Button)findViewById(R.id.buttonAddUpdate);
buttonAddUpdate.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
saveRecord();
}
});
mListView = (ListView)findViewById(R.id.listView);
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View
view, int position, long id) {
Log.d(TAG, "the id is logged " + Long.toString(id));
String nextId = String.valueOf(id+1);
Intent intent = new Intent(view.getContext(),DetailActivity.class);
intent.putExtra("key" ,mDB.getWord(id)+"");
intent.putExtra("value",mDB.getDefinition(id)+"");
intent.putExtra("nextId",nextId+"");
startActivity(intent);
}
});
mListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(MainActivity.this,
"Records deleted = " + mDB.deleteRecord(id),
Toast.LENGTH_SHORT).show();
updateWordList();
return true;
}
});
updateWordList();
}
private void saveRecord() {
mDB.saveRecord(mEditTextWord.getText().toString(),
mEditTextDefinition.getText().toString());
mEditTextWord.setText("");
mEditTextDefinition.setText("");
updateWordList();
}
private void updateWordList() {
SimpleCursorAdapter simpleCursorAdapter = new
SimpleCursorAdapter( this,
android.R.layout.simple_list_item_1,
mDB.getWordList(),
new String[]{"word"},
new int[]{android.R.id.text1},
0);
mListView.setAdapter(simpleCursorAdapter);
}
#Override //added following https://stackoverflow.com/a/27192897/5774375
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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"
android:fitsSystemWindows="true"
tools:context="com.myappshop.myapp.MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_main" />
</android.support.design.widget.CoordinatorLayout>
The minimum API that I'v set is 15.
I've looked at similar answers on SO, like this but none resolve my probelm. So appreciate your help.
UPDATE: DetailActivity.java added:
public class DetailActivity extends AppCompatActivity {
private static final String TAG = DetailActivity.class.getSimpleName();
Button shareBtn, nextBtn, prevBtn, indexBtn ;
DictionaryDatabase mDB;
TextView title, body; //Globally Declaration
String nextId;
int id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
try{
String key = getIntent().getStringExtra("key");
String value = getIntent().getStringExtra("value");
String idString = getIntent().getStringExtra("nextId");
id = Integer.parseInt(idString) + 1; //to be used to rener the next item
title = (TextView) findViewById(R.id.title);
title.setText(key);
body = (TextView) findViewById(R.id.body);
body.setText(value);
}
catch(Exception e){
e.printStackTrace();
}
final Button button = (Button) findViewById(R.id.shareBtn);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, body.getText().toString());
sendIntent.setType("text/plain");
startActivity(sendIntent);
}
});
shareBtn = (Button) findViewById(R.id.shareBtn);
//render the next word
mDB = new DictionaryDatabase(this);
nextBtn = (Button) findViewById(R.id.nextBtn);
prevBtn = (Button) findViewById(R.id.prevBtn);
indexBtn = (Button) findViewById(R.id.indexBtn);
nextBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
id+=1;
Log.d(TAG, "the next item to be fetched has id: " + Long.toString(id));
Log.d(TAG, "return value is: " + mDB.getWord(id));
if (mDB.getWord(id) != "") {
String key = mDB.getWord(id);
String value = mDB.getDefinition(id);
title = (TextView) findViewById(R.id.title);
title.setText(key);
body = (TextView) findViewById(R.id.body);
body.setText(value);
prevBtn.setVisibility(View.VISIBLE);
} else {
finish();
}
}
});
prevBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
id-=1;
if (mDB.getWord(id) != "") {
String key = mDB.getWord(id);
String value = mDB.getDefinition(id);
title = (TextView) findViewById(R.id.title);
title.setText(key);
body = (TextView) findViewById(R.id.body);
body.setText(value);
nextBtn.setVisibility(View.VISIBLE);
} else {
finish();
}
}
});
indexBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
finish();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}
You have to inflate your menu.xml before you can call its menu items. Add this before onOptionsItemSelected()
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
Sorry about that. I also noticed that you didn't declare your toolbar in your activitys' onCreate(). You would have to declare your toolbar before placing menu items on it. Add this to your activity's onCreate method.
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Also, make sure you include your toolbar/appbar layout in your main layout for this activity.

why my splash screen is so long

I'm trying to implement a splash screen on my app. After the loading of the splash screen, I have two issues.
If the user is connected, an activity is started. If not, an other is started.
But, with my implementation, when the user is connected, the splash screen is very long (8 or 9 sec), but I don't know why.
That is my first class which check if the user is connected, and it load some shared preferences? So maybe it's that?
public class AnnaActivity extends AppCompatActivity {
public PrefManager pref;
private AllRequest req;
private static final String REQUEST_TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.pref = new PrefManager(getApplicationContext());
boolean isco = pref.getIsConnect();
if (isco) {
Log.e("SPLASH", "IsConnected");
Intent loginActivity = new Intent(this, NavigationDrawerActivity.class);
startActivity(loginActivity);
finish();
} else {
Log.e("SPLASH", "launch login activity");
Intent loginActivity = new Intent(this, MainActivity.class);
startActivity(loginActivity);
finish();
}
}
}
that is my splash drawable
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#color/colorPrimaryDark"/>
<item android:bottom="8dp"
android:top="8dp"
android:left="8dp"
android:right="8dp">
<bitmap android:gravity="center"
android:src="#mipmap/ic_launcher"
android:antialias="true"/>
</item>
</layer-list>
And my splach style
<style name="SplashTheme" parent="Theme.AppCompat.Light.NoActionBar">
<item name="android:windowBackground">#drawable/splash_drawable</item>
</style>
(Edit post) The navigation drawerActivity
public class NavigationDrawerActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, Response.Listener, Response.ErrorListener{
public TextView TextViewEmailAddress;
public TextView TextViewLogin;
private PrefManager pref;
private AllRequest req;
public RequestQueue mQueue;
private static final String REQUEST_TAG = "LogOutActivity";
private String address;
private String login;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navigation_drawer);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
// fab.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View view) {
// Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
// .setAction("Action", null).show();
// }
// });
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();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
View header = navigationView.getHeaderView(0);
this.TextViewEmailAddress = (TextView)header.findViewById(R.id.textView_drawer_mail);
this.TextViewLogin = (TextView)header.findViewById(R.id.textView_drawer_login);
this.pref = new PrefManager(getApplicationContext());
this.req = new AllRequest(getApplicationContext());
this.mQueue = CustomVolleyRequestQueue.getInstance(this.getApplicationContext())
.getRequestQueue();
address = this.pref.getEmail();
login = this.pref.getLogin();
this.TextViewEmailAddress.setText(address);
this.TextViewLogin.setText(getText(R.string.text_view_login_drawer) + " " + login);
}
#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.navigation_drawer, 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_mon_compte) {
Intent intent = new Intent(NavigationDrawerActivity.this, MyAccountActivity.class);
startActivity(intent);
} else if (id == R.id.nav_deconnection) {
deconnexion();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private void deconnexion(){
LayoutInflater factory = LayoutInflater.from(this);
final View alertDialogView = factory.inflate(R.layout.alertdialog_logout, null);
final AlertDialog.Builder adb = new AlertDialog.Builder(this);
adb.setView(alertDialogView);
adb.setTitle(R.string.alertDialod_logout_Title);
adb.setPositiveButton((R.string.alertDialog_logout_PositiveBtnName), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String accessToken = pref.getAccessToken();
req.revokeTokenRequest(REQUEST_TAG, accessToken, NavigationDrawerActivity.this, NavigationDrawerActivity.this);
pref.logout();
Intent intent = new Intent(NavigationDrawerActivity.this, MainActivity.class);
startActivity(intent);
}
});
adb.setNegativeButton((R.string.alertDialog_logout_NegativeBtnName), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
adb.show();
}
#Override
public void onErrorResponse(VolleyError error) {
Log.e("errrrrrror :(", "it's not working");
}
#Override
public void onResponse(Object response) {
Log.e("pololololo","it's working :D");
}
}

How to save image from one activity to another

So i start on one screen that is for building an image. my build mode
When i click on stencil i go into a new activity that looks like this stencil picker
While in my stencil picker i have an onclick method for the pictures using a switch case. what i need to do is remember what image i clicked on and apply that image to the previous page. I need to also be able to save the images that are added to the build mode so they can stack ontop of each other (but that is a secondary problem).
here is my code for the build page
public class BuildMode extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, AdapterView.OnItemSelectedListener {
private Button mStencilButton;
//private Button mColorButton;
private Button mUndoButton;
private Button mRedoButton;
private Spinner mColorSpinner;
private ImageView mImageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_build_mode);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//bit map to get stencil selected and place into build mode
// Bundle extras = getIntent().getExtras();
// byte[] byteArray = extras.getByteArray("picture");
// Bitmap bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
// ImageView image = (ImageView) findViewById(R.id.egg_image);
// image.setImageBitmap(bmp);
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();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
mStencilButton = (Button) findViewById(R.id.stencil_button);
// mColorButton = (Button) findViewById(R.id.color_button);
mUndoButton = (Button) findViewById(R.id.undo_button);
mRedoButton = (Button) findViewById(R.id.redo_button);
mColorSpinner = (Spinner) findViewById(R.id.colors_spinner);
mColorSpinner.setOnItemSelectedListener(this);
mStencilButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(BuildMode.this, StencilList.class);
startActivity(intent);
}
});
mUndoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
mRedoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
mColorSpinner = (Spinner) findViewById(R.id.colors_spinner);
mColorSpinner.setOnItemSelectedListener(this);
}
#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.build_mode, 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.about_us) {
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_manage_build) {
// Handle the camera action
} else if (id == R.id.nav_gallery_build) {
Intent intent = new Intent(BuildMode.this, PreviewMode.class);
startActivity(intent);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
switch (position) {
case 0:
// mImageView.setBackgroundColor(Color.WHITE);
break;
case 1:
// mImageView.setBackgroundColor(Color.YELLOW);
break;
case 2:
// mImageView.setBackgroundColor(Color.GREEN);
break;
case 3:
// mImageView.setBackgroundColor(Color.BLUE);
break;
case 4:
// mImageView.setBackgroundColor(Color.RED);
break;
case 5:
// mImageView.setBackgroundColor(Color.BLACK);
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
and my code for the stencil page
public class StencilList extends AppCompatActivity {
private ImageView mStencil1;
private Bitmap bmp;
private byte[] byteArray;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stencil_list);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
public void useStencil(View view) {
// Intent intent = new Intent(this, BuildMode.class);
switch (view.getId()) {
case R.id.stencil_image_1:
// intent.putExtra("picture", byteArray);
// startActivity(intent);
break;
case R.id.stencil_image_2:
break;
case R.id.stencil_image_3:
break;
case R.id.stencil_image_4:
break;
case R.id.stencil_image_5:
break;
case R.id.stencil_image_6:
break;
case R.id.stencil_image_7:
break;
case R.id.stencil_image_8:
break;
case R.id.stencil_image_9:
break;
case R.id.stencil_image_10:
break;
case R.id.stencil_image_11:
break;
case R.id.stencil_image_12:
break;
case R.id.stencil_image_13:
break;
case R.id.stencil_image_14:
break;
}
}
private void imageClicked()
{
}
}
I would try this:
When you click on the stencil option, you need a way to know the position clicked by the user
Perhaps, you can easily create a variable to set when a stencil is clicked then pass that as an Extra to your previous activity
Once you are in the other activity, keep a simple integer array of your image drawables.
Finally, get the corresponding image from using the index you received through the intent. That should work!
I hope this helps!

ToolBar's Menu item is not clickable

I am having cart icon on ToolBar.When I try to click,it didn't show any action for a long time.After keep on clicking it, Toast message that I set is enabled or the app is crashed.
Please help me to fix it.
My Code is:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
badgeLayout = (RelativeLayout) menu.findItem(R.id.badge).getActionView();
mCounter = (TextView) badgeLayout.findViewById(R.id.counter);
badgeLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "Cart is Working", Toast.LENGTH_SHORT).show();
Intent next = new Intent(context, ProductActivity.class);
startActivity(next);
}
});
return true;
}
UPDATE:
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, SearchView.OnCloseListener, SearchView.OnQueryTextListener {
public static final String MyPREFERENCES = "Preference";
public static final String SEARCHING_DATA = "DATA_SEARCH";
public static String strTabName;
public static TextView mCounter;
public static RelativeLayout badgeLayout;
public ArrayList<String> values;
Toolbar toolbar;
Context context;
Config config;
ArrayList<String> tabName = new ArrayList<String>();
SharedPreferences pref;
TextView txtDash_Title, txtDash_Des;
String passQuery;
FragmentManager mFragmentManager;
FragmentTransaction mFragmentTransaction;
String possibleEmail;
String GOOGLE_USERNAME;
private int count = 0;
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = this;
pref = context.getSharedPreferences(MyPREFERENCES, MODE_PRIVATE);
setupToolbar();
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();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
txtDash_Title = (TextView) findViewById(R.id.dashboard_txt_title);
txtDash_Des = (TextView) findViewById(R.id.dashboard_txt_des);
TextView myTextview = (TextView) findViewById(R.id.textView);
if (haveNetworkConnection())
new TabNameSync().execute();
else
Toast.makeText(context, "No Network Connection", Toast.LENGTH_SHORT).show();
setupCollapsingToolbar();
getGOOGLEUSERNAME();
}
private void getGOOGLEUSERNAME() {
Cursor c = getApplication().getContentResolver().query(ContactsContract.Profile.CONTENT_URI, null, null, null, null);
c.moveToFirst();
GOOGLE_USERNAME = c.getString(c.getColumnIndex("display_name"));
Log.e("Google Username", GOOGLE_USERNAME);
c.close();
}
private void setupCollapsingToolbar() {
final CollapsingToolbarLayout collapsingToolbar = (CollapsingToolbarLayout) findViewById(
R.id.collapse_toolbar);
collapsingToolbar.setTitleEnabled(false);
}
private void setupToolbar() {
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Welcome to Scoop Shop!");
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.nav_camera) {
} 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;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
badgeLayout = (RelativeLayout) menu.findItem(R.id.badge).getActionView();
mCounter = (TextView) badgeLayout.findViewById(R.id.counter);
badgeLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "Cart Working", Toast.LENGTH_SHORT).show();
Intent next = new Intent(context, ProductActivity.class);
startActivity(next);
}
});
// SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
// SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
// searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
// searchView.setSubmitButtonEnabled(false);
//// searchView.getOutlineProvider();
// searchView.setOnQueryTextListener(this);
// searchView.setOnCloseListener(this);
// return super.onCreateOptionsMenu(menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_search:
break;
case R.id.badge:
Toast.makeText(context, "Cart is Working", Toast.LENGTH_SHORT).show();
/* Intent next = new Intent(context, ProductActivity.class);
startActivity(next);*/
return true;
default:
return super.onOptionsItemSelected(item);
}
return super.onOptionsItemSelected(item);
}
}
The issue may already be closed, but I found possible cause:
if you used Relative Layout in your .xml file, neighboring elements can cover your toolbar.
So, your toolbar must be in top of views in your .xml file.
It's working for me.
You should go with OnOptionsItemSelected()
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.badge:
Toast.makeText(context, "Cart is Working", Toast.LENGTH_SHORT).show();
Intent next = new Intent(context, ProductActivity.class);
startActivity(next);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
For more information check this link: http://developer.android.com/guide/topics/ui/menus.html
May be the problem is you are not calling super.onOptionsItemSelected(item) when badge is clicked. Change your method as follows :-
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item)
switch (item.getItemId()) {
case R.id.action_search:
break;
case R.id.badge:
Toast.makeText(context, "Cart is Working", Toast.LENGTH_SHORT).show();
/* Intent next = new Intent(context, ProductActivity.class);
startActivity(next);*/
break;
default:
break;
}
return true;
}

Categories

Resources