Actionbar buttons not working - android

I am new to android development.I have made an app where the MainActivity consists of a Gridview with images and ActivityTwo is the fullscreen view of the selected image.I am trying to add a back button on the actionbar.The icon is visible but it is not clickable.Also i tried to add other menu items which are also visible but nothing happens on touching them.I have also tried adding onClickListener to the menu items as suggested in some posts but it didn't seem to work.
Below is the ActivityTwo code.
public class ActivityTwo extends ActionBarActivity implements OnClickListener {
protected int currentPosition;
Button share,back;
ImageView imageView;
ViewPager viewPager;
private Toolbar toolbar;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_two);
toolbar= (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
share = (Button)findViewById(R.id.button1);
share.setOnClickListener(this);
back=(Button)findViewById(R.id.button2);
back.setOnClickListener(this);
// get intent data
Intent i = getIntent();
// Selected image id
final int position = i.getExtras().getInt("position");
viewPager = (ViewPager) findViewById(R.id.view_pager);
ImagePagerAdapter adapter = new ImagePagerAdapter();
viewPager.setAdapter(adapter);
viewPager.setCurrentItem(position);
viewPager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int arg0) {
// TODO Auto-generated method stub
currentPosition = arg0;
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
});
}
#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();
if (id == R.id.action_settings) {
return true;
}
if
(id==R.id.home)
{
NavUtils.navigateUpFromSameTask(this);
}
return super.onOptionsItemSelected(item);
}
public class ImagePagerAdapter extends PagerAdapter {
Integer[] icons = MainActivity.mThumbIds;
#Override
public int getCount() {
return icons.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Context context = ActivityTwo.this;
imageView = new ImageView(context);
//ImageView imageView = (ImageView)findViewById(R.id.imageView);
// int padding = context.getResources().getDimensionPixelSize(
// R.dimen.padding_large);
imageView.setPadding(5, 5, 5, 5);
imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
imageView.setImageResource(icons[position]);
imageView.setTag(position);
((ViewPager) container).addView(imageView, 0);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ImageView) object);
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v==share){
ImageView Imgv = (ImageView)viewPager.findViewWithTag(viewPager.getCurrentItem());
Drawable mDrawable = Imgv.getDrawable();
Bitmap mBitmap = ((BitmapDrawable)mDrawable).getBitmap();
String path = Images.Media.insertImage(getContentResolver(),
mBitmap, "Image Description", null);
Uri uri = Uri.parse(path);
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
shareIntent.setType("image/*");
startActivity(Intent.createChooser(shareIntent, "Share Image")); }
if(v==back)
{
finish();
}
}
}

Try to add this code to your toolbar for navigating back
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
For another item in your toolbar
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
Toast.makeText(context, "setting", Toast.LENGTH_SHORT).show();
break;
case R.id.action_share:
Toast.makeText(context, "share", Toast.LENGTH_SHORT).show();
break;
}
}
Hope this help

To make your app icon "clickable" as a back button, your Activities must follow a parent-child hierarchy.
Example:
Activity A is your main Activity.
Pressing something (say a ListView item or GridView item) will start Activity B.
In this way Activity A is what's called a parent Activity to Activity B.
You define this in XML in your manifest like so:
<activity
android:name="com.example.android.ActivityA"
android:label="#string/title_activity_a" />
<activity
android:name="com.example.android.ActivityB"
android:label="#string/title_activity_b"
android:parentActivityName="com.example.android.ActivityA">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.android.ActivityA" />
</activity>
This will make the app icon appear with a back arrow ( < ) to the left of it.
We then must handle the click event.
We so this from within our onOptionsItemSelected method in Activity B like so:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
// Create an intent to start Activity A.
Intent intent = new Intent(ActivityB.this, ActivityA.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
android.R.id.home is the ID of the click event we are listening for.
Sometimes you may wish to simulate a back button press instead of starting Activity A fresh with an intent. You could achieve that like so:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
// Simulate back button press.
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}

Related

How to Use Navigateup Back From Thrird Activity to Second Activity using Intent

I am developing an android application. In this application,I have 3 Activity one as Title Activity and another one as Subtitle Activity and another one is detail Activity
Now i want to navigate up from one activity(Subtitle Activity) to parent activty(Title Activity) by using the below code i perform that operation
SubTitleActivity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.subcategory_activity);
actionBar=getSupportActionBar();
listView2= (ListView) findViewById(R.id.listView2);
Intent intent= getIntent();
final String selectedData = intent.getStringExtra("selectedItem");
actionBar.setTitle(selectedData);
dbHelper = new SqlLiteDbHelper(this);
try {
dbHelper.openDataBase();
} catch (SQLException e) {
e.printStackTrace();
}
sqLiteDatabase=dbHelper.getReadableDatabase();
cursor=dbHelper.getsubcategory(sqLiteDatabase,selectedData);
String[] from = new String[] { dbHelper.SUBCATEGORY };
int[] to = new int[] {R.id.subcategory };
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,R.layout.subcategory_row,cursor,from,to);
adapter.notifyDataSetChanged();
listView2.setAdapter(adapter);
listView2.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Cursor cursor = (Cursor) (listView2.getItemAtPosition(position));
String selectedItem = cursor.getString(0);
Intent intent = new Intent(SubcategoryActivity.this, DetailActivity.class);
intent.putExtra("selectedItem", selectedItem);
startActivity(intent);
}
});
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id==android.R.id.home)
{
NavUtils.navigateUpFromSameTask(this);
}
return super.onOptionsItemSelected(item);
}
}
Manifest.xml
<activity
android:name=".SubcategoryActivity"
android:label="#string/title_activity_subcategory" >
<meta-data android:name="android.support.PARENT_ACTIVITY" android:value=".MainActivity"></meta-data>
</activity>
Now i don't know how to Move From My Detail Activity to Subtile Activity how can we perform that??
DetailActivity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.detail_activity);
actionBar=getSupportActionBar();
detailtext= (TextView) findViewById(R.id.detail);
imageView= (ImageView) findViewById(R.id.images);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Intent intent= getIntent();
final String selectedData = intent.getStringExtra("selectedItem");
actionBar.setTitle(selectedData);
dbHelper = new SqlLiteDbHelper(this);
try {
dbHelper.openDataBase();
} catch (SQLException e) {
e.printStackTrace();
}
sqLiteDatabase = dbHelper.getReadableDatabase();
cursor=dbHelper.getdetails(sqLiteDatabase, selectedData);
if(cursor.moveToFirst())
{
detailtext.setText(cursor.getString(0));
}
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id==android.R.id.home)
{
onBackPressed();
}
Do something like this in your DetailsActivity code:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
For more info read about the Tasks and Back Stack (Especially the Using Intent Flags part) here : http://developer.android.com/guide/components/tasks-and-back-stack.html
Use
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setNavigationOnClickListener(View.OnClickListener);
and put click listener like:
new View.OnClickListener() {
#Override
public void onClick(View view) {
YourActivity.this.onBackPressed();
}

Silly errors (beginner)

I have a first activity ("Home"), with two buttons: one is called About and leads to activity About and the second is named List and leads to the activity List.
Manifest.xml should be fine, but I get a load of tiny petty errors I can't fix up by myself, regrettably.
Home.class is the following
Public class Home extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Button AboutButton = (Button)findViewById(R.id.About);
AboutButton.setOnClickListener(new View.OnClickListener()){
#Override
public void onClick(View view); {
Intent openAbout = new Intent(Home.this, About.class);
startActivity(openAbout);
}
}
Button ListButton = (Button)findViewById(R.id.List);
ListButton.setOnClickListener(new View.onClickListener());{
#Override
public void onClick(View view); {
Intent openList = new Intent(Home.this, List.class);
startActivity(openList);
}
}
}
#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_home, 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);
}
}
while About.class is like this
public class About extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_about);
Button ReturnButton = (Button)findViewById(R.id.Return);
ReturnButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent returnhome = new Intent(About.this, Home.class);
startActivity(returnhome);
}
public void onClick(View view); {
Intent returnhome = new Intent(About.this, Home.class);
startActivity(returnhome);
}
}
}
#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_about, 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);
}
}
and List is like this:
public class List extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
Button ReturnButton = (Button)findViewById(R.id.Return);
ReturnButton.setOnClickListener(new View.OnClickListener()){
#Override
public void onClick(View view) {
Intent returnhome = new Intent(About.this, Home.class);
startActivity(returnhome);
}
}
}
#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_list, 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);
}
}
I get lot of red light bulbs, saying, for instance that ")" or ";" is expected or (worse) onClickListener cannot be resolved
Last but not least: I copied this code online and I was wondering why after "View" there is a "view"; what does it mean?
I copied your code and I see fails everywhere... let me explain you what's going on ...
HOME CLASS
1.- You have to remove the ")"
2.- You don't have to ";" when you call onClick()
3.- When you are don on your onClick() NOW you have to close it, you missed the ");"
AboutButton.setOnClickListener(new View.OnClickListener()){ //<-- Just remove one
#Override
public void onClick(View view); { //<-- Remove this ";"
Intent openAbout = new Intent(Home.this, About.class);
startActivity(openAbout);
}
}//Here goes ");"
4.- The ListButton has the same issues so just fix it as you will fix the first one.
ABOUT CLASS
1.-On this case you have the setOnClickListener() ok, BUT why you have two onClick(View view)? It's not necessary just remove one of them.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_about);
Button ReturnButton = (Button) findViewById(R.id.Return);
ReturnButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent returnhome = new Intent(About.this, Home.class);
startActivity(returnhome);
}
});
}
LIST CLASS
1.-Well in your List class you have made the same error as the first one... Your onClickListener() it's wrong.
2.-Once again you included an unnecessary ")" on new View.OnClickListener() just remove it,
3.-Another fail that I'm seeing is that you are trying to make an Intent but you are refering that you are on About.this and you are NOT. You are on List class so you have ot put List.this because the first parameter refers :
A Context as its first parameter (this is used because the Activity class is a subclass of Context)
More information about Intents
4.- You need to close again the setOnClickListener()
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
Button ReturnButton = (Button)findViewById(R.id.Return);
ReturnButton.setOnClickListener(new View.OnClickListener()){ //<-- remove one ")"
#Override
public void onClick(View view) {
Intent returnhome = new Intent(About.this, Home.class); //<-- Remove About.this and put List.this
startActivity(returnhome);
}
}//<-- Close the setOnClickListener() with ");"
}
It's okay guy, this is your first question and I'll answer it, but NOW as I've made the favor to take my time and explain to you what was wrong on your code take your time to :
How do I as a question on StackOverflow
Learn some Android basics
And the most IMPORTANT THING
DO NOT COPY PASTE AN INTERNET CODE if you don't know the basics, I mean you can copy paste the code, but you'll face with this problem every time you do this, so first of all read the tutorial, make an examples, and you'll improve every day.

error whilst passing values between activities

I have an activity which has an edit text which becomes visible when a button is clicked. I fill the edit text up and click another button. On clicking this button the edit text content must be sent to another activity.The first activity takes the edit text and queries a list of data from my Parse database and shows it in a ListView in the Second Activity.But whenever i click the first button(after entering the string) the app crashes.This is the first activity
public class MainActivity extends ActionBarActivity {
String name;
EditText search;
Button g;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setUpSpinners();
Parse.initialize(this, "AAh5US7zhbYyFBexsv07cjo34ZZiB7KNe9SuTv7e",
"eKUG1pYaV50hVyDC9d4qZc4qf1dCtOTqnX92eGJV");
PushService.setDefaultPushCallback(this, MainActivity.class);
ParseInstallation.getCurrentInstallation();
search = (EditText) findViewById(R.id.search);
g = (Button) findViewById(R.id.Go);
}
#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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void byName(View v) {
search.setVisibility(View.VISIBLE);
search.requestFocus();
g.setVisibility(View.VISIBLE);
}
public void Go(View v) {
name = search.getText().toString();
final Intent i;
i = new Intent(MainActivity.this, ResterauntList1.class);
i.putExtra("restrauntName", name);
startActivity(i);
}
}
In the above byName is the onClick for making the EditText visible, and Go is the onClick for getting my EditText string and passing it to the next activity. The second activity is below
public class ResterauntList1 extends Activity {
String rValue;
ArrayAdapter<String> adapter;
ProgressDialog mProgressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_resteraunt_list1);
Bundle bdl = getIntent().getExtras();
rValue = bdl.getString("restrauntName");
setContentView(R.layout.activity_resteraunt_list);
populateList(rValue, "name");
}
private void populateList(final String Value, final String Key) {
ParseQueryAdapter.QueryFactory<ParseObject> factory = new ParseQueryAdapter.QueryFactory<ParseObject>() {
#Override
#SuppressWarnings({ "unchecked", "rawtypes" })
public ParseQuery create() {
ParseQuery query = new ParseQuery("resdb");
query.whereEqualTo(Key, Value);
return query;
}
};
ParseQueryAdapter<ParseObject> adapter = new ParseQueryAdapter<ParseObject>(
this, factory);
adapter.setTextKey("name");
adapter.addOnQueryLoadListener(new OnQueryLoadListener<ParseObject>() {
#Override
public void onLoading() {
mProgressDialog = new ProgressDialog(ResterauntList1.this);
mProgressDialog.setTitle("Searching for " + Value);
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.show();
}
#Override
public void onLoaded(List<ParseObject> objects, Exception e) {
mProgressDialog.dismiss();
}
});
final ListView listView = (ListView) findViewById(R.id.restListView1);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
ParseObject object = (ParseObject) listView
.getItemAtPosition(position);
String Id = object.getObjectId();
Intent i = new Intent(getApplicationContext(),
SingleRestraunt.class);
i.putExtra("restId", Id);
startActivity(i);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.resteraunt_list1, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
The error as stated above occurs when I click the Go button.The error is
09-02 14:58:46.443: E/AndroidRuntime(3061): Process: com.example.gastronomaapp, PID: 3061
09-02 14:58:46.443: E/AndroidRuntime(3061): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.gastronomaapp/com.example.gastronomaapp.ResterauntList1}: java.lang.NullPointerException
Any idea where I am making a mistake? The funniest thing almost the same code has worked in another part of my app. absolutely clueless whats wrong.
Bundle bdl = getIntent().getExtras();
rValue = bdl.getString("restrauntName");
change to
rValue = getIntent().getStringExtra("restrauntName");
You put the string directly on the intent, not packaged in a bundle.

android fragment onorientationchange issue

I created a simple project that Button in Activity click to Show Toast from Fragment.Works fine when just click Button, but after orientation changed and clicking Button occurs error.
public class MainActivity extends Activity {
PlaceholderFragment pf;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pf = new PlaceholderFragment();
Button b = (Button)findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
pf.showToast();
}
});
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, pf)
.commit();
}
}
#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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
Log.i("TAG", "onCreateView");
return rootView;
}
public void showToast(){
Toast.makeText(getActivity(), "Show Toast from PlaceholderFragment", Toast.LENGTH_SHORT).show();
}
#Override
public void onAttach(Activity activity) {
// TODO Auto-generated method stub
super.onAttach(activity);
Log.i("TAG", "onAttach");
}
#Override
public void onDetach() {
// TODO Auto-generated method stub
super.onDetach();
Log.i("TAG", "onDetach");
}
}
}
I found out Fragment was calling onAttach and onDetach after orientating. How can i fix this problem?
When the device Orientation changes, the activity in which the fragment sits is by default destroyed and created again. You can avoid these changes by adjusting the android:configChanges in the manifest file. This code should work:
android:configChanges="keyboardHidden|orientation"

Setting OnClickListener on the actionbar home icon makes the icon loose the press state

Setting the following makes the home icon show a press state:
actionBar.setHomeButtonEnabled(true);
But, after setting OnClickListener the home icon stops showing the press state:
ImageView iconImage = (ImageView) activity.findViewById(android.R.id.home);
iconImage.setOnClickListener(new android.view.View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
Any idea on how to prevent disabling the press state?
To handle the click on the home icon , you do not need to set onClickListener, you need to do the following..
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == android.R.id.home) { //app icon in action bar clicked; go back
//do something
return true;
}
return super.onOptionsItemSelected(item);
}
public class MainActivity extends Activity {
Fragment fr;
FragmentManager fm;
Button btn1,btn2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActionBar actionBar = getActionBar();
actionBar.setHomeButtonEnabled(true);
btn1=(Button)findViewById(R.id.button1);
btn2=(Button)findViewById(R.id.button2);
fm = getFragmentManager();
btn1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
fr = new frag22();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.fragment, fr);
ft.commit();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
// TODO Auto-generated method stub
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
if(item.getItemId() == android.R.id.home) { //app icon in action bar clicked; go back
//do something
Toast.makeText(getApplicationContext(), "set click", Toast.LENGTH_LONG).show();
return true;
}
return super.onOptionsItemSelected(item);
}
}

Categories

Resources