I am trying to display a pop up window when i click on a menu overflow item. I have written some code also for that. But it outputs nothing.
Here is some code:
#Override
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()) {
case R.id.settings_id:
displayPopupWindow();
return true;
case R.id.about_us_id:
return true;
case R.id.logout_id:
startActivity(new Intent(HomePage.this,MainActivity.class));
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void displayPopupWindow() {
PopupWindow popup = new PopupWindow(this);
View layout = getLayoutInflater().inflate(R.layout.popup, null);
popup.setContentView(layout);
popup.setOutsideTouchable(true);
popup.setFocusable(true);
popup.showAtLocation(layout, Gravity.CENTER, 0, 0);
}
My Xml file Code is below:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:background="#color/colorPrimary">
<TextView
android:text="TextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="165dp"
android:id="#+id/textView"
tools:text="This is a Pop Up Window!"
android:textSize="36sp"
android:textStyle="normal|bold"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="19dp"
android:layout_marginStart="19dp"
android:textAlignment="center"
android:fontFamily="sans-serif" />
</RelativeLayout>
Where is the error? Please help me.
Here is your solution,
MainActivity.java
public class MainActivity extends Activity {
private PopupWindow mPopupWindow;
private Button btnClosePopup;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.items, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.phone:
Toast.makeText(getBaseContext(), "You selected Phone", Toast.LENGTH_SHORT).show();
break;
case R.id.computer:
Toast.makeText(getBaseContext(), "You selected Computer", Toast.LENGTH_SHORT).show();
break;
case R.id.gamepad:
Toast.makeText(getBaseContext(), "You selected Gamepad", Toast.LENGTH_SHORT).show();
break;
case R.id.camera:
Toast.makeText(getBaseContext(), "You selected Camera", Toast.LENGTH_SHORT).show();
initiatePopupWindow();
break;
case R.id.video:
Toast.makeText(getBaseContext(), "You selected Video", Toast.LENGTH_SHORT).show();
break;
case R.id.email:
Toast.makeText(getBaseContext(), "You selected EMail", Toast.LENGTH_SHORT).show();
break;
}
return true;
}
private void initiatePopupWindow() {
try {
LayoutInflater inflater = (LayoutInflater) MainActivity.this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.popup,
(ViewGroup) findViewById(R.id.popup_element));
mPopupWindow = new PopupWindow(layout, 300, 370, true);
mPopupWindow.showAtLocation(layout, Gravity.CENTER, 0, 0);
btnClosePopup = (Button) layout.findViewById(R.id.btn_close_popup);
btnClosePopup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mPopupWindow.dismiss();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}
popup.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/popup_element"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#444444"
android:orientation="vertical"
android:padding="10sp">
<TextView
android:id="#+id/txtView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5sp"
android:text="Hello!" />
<Button
android:id="#+id/btn_close_popup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Close" />
</LinearLayout>
Related
When i open this activity, drawer is already opened by default. When i try to close the drawer, it doesn't. In short drawer is malfunctioning. I have attached both XML code & JAVA code.
This is XML File Code:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
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:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<android.support.design.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/bg_home">
<include
android:id="#+id/action_bar"
layout="#layout/actionbar"
/>
<android.support.design.widget.NavigationView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:id="#+id/nav_view"
app:headerLayout="#layout/navigation"
app:menu="#menu/drawer_menu"/>
<android.support.design.widget.FloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_marginRight="20dp"
android:layout_marginBottom="210dp"
android:src="#drawable/add_to_cart"
android:elevation="6dp"
android:id="#+id/fab_place_order"
app:pressedTranslationZ="12dp"
app:backgroundTint="#color/fabOrder"
android:visibility="invisible"
/>
<android.support.design.widget.FloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_marginRight="20dp"
android:layout_marginBottom="150dp"
android:src="#drawable/ic_account_balance_wallet_black_24dp"
android:elevation="6dp"
android:id="#+id/fab_balance"
app:pressedTranslationZ="12dp"
app:backgroundTint="#color/fabBalance"
android:visibility="invisible"
/>
<android.support.design.widget.FloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_marginRight="20dp"
android:layout_marginBottom="90dp"
android:src="#drawable/ic_exit_to_app_black_24dp"
android:elevation="6dp"
android:id="#+id/fab_logout"
app:pressedTranslationZ="12dp"
app:backgroundTint="#color/fabExit"
android:visibility="invisible"
/>
<android.support.design.widget.FloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_marginRight="20dp"
android:layout_marginBottom="20dp"
android:src="#drawable/menu"
android:elevation="6dp"
android:id="#+id/fab_menu"
app:pressedTranslationZ="12dp"
android:backgroundTint="#color/fabMain"
/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ProgressBar
android:id="#+id/progressBar"
style="?android:attr/progressBarStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
<TextView
android:id="#+id/label1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_marginBottom="230dp"
android:layout_marginEnd="80dp"
android:layout_marginRight="70dp"
android:text="Place Order"
android:textColor="#003200"
android:textStyle="bold"
android:visibility="invisible" />
<TextView
android:id="#+id/label2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignEnd="#+id/label1"
android:layout_alignLeft="#+id/label1"
android:layout_alignParentBottom="true"
android:layout_alignRight="#+id/label1"
android:layout_marginBottom="170dp"
android:text="Check Balance"
android:textColor="#000032"
android:textStyle="bold"
android:visibility="invisible" />
<TextView
android:id="#+id/label3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignEnd="#+id/label1"
android:layout_alignParentBottom="true"
android:layout_alignRight="#+id/label1"
android:layout_marginBottom="110dp"
android:text="Logout"
android:textColor="#320000"
android:textStyle="bold"
android:visibility="invisible" />
</RelativeLayout>
</android.support.design.widget.CoordinatorLayout>
</android.support.v4.widget.DrawerLayout>
This is JAVA File Code:
public class HomeActivity extends AppCompatActivity {
ConnectionDetector connectionDetector = new ConnectionDetector(this);
DatabaseHelper helper = new DatabaseHelper(this);
Handler handler = new Handler();
FloatingActionButton fab_menu,fab_balance,fab_logout,fab_order;
Animation fabOpen,fabClose,fabClockwise,fabAnticlockwise;
boolean isOpen = false, status = false;
ProgressBar progressBar;
private boolean isUserClickedBackButton = false;
private DrawerLayout drawerLayout;
TextView t1,t2,t3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
helper.startFirebaseDB();
Toolbar toolbar = findViewById(R.id.action_bar);
toolbar.setTitleTextColor(getResources().getColor(R.color.white));
setSupportActionBar(toolbar);
drawerLayout = findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this,drawerLayout,toolbar,R.string.navigation_drawer_open,R.string.navigation_drawer_close);
toggle.syncState();
progressBar = findViewById(R.id.progressBar);
fab_menu = findViewById(R.id.fab_menu);
fab_menu.setEnabled(false);
fab_order = findViewById(R.id.fab_place_order);
fab_balance = findViewById(R.id.fab_balance);
fab_logout = findViewById(R.id.fab_logout);
t1 = findViewById(R.id.label1);
t2 = findViewById(R.id.label2);
t3 = findViewById(R.id.label3);
fabOpen= AnimationUtils.loadAnimation(getApplicationContext(),R.anim.fab_open);
fabClose= AnimationUtils.loadAnimation(getApplicationContext(),R.anim.fab_close);
fabClockwise= AnimationUtils.loadAnimation(getApplicationContext(),R.anim.rotate_clockwise);
fabAnticlockwise= AnimationUtils.loadAnimation(getApplicationContext(),R.anim.rotate_anticlockwise);
handler.postDelayed(new Runnable() {
#Override
public void run() {
progressBar.setVisibility(View.GONE);
fab_menu.setEnabled(true);
}
},2000);
fab_menu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(isOpen)
{
fab_order.startAnimation(fabClose);
fab_balance.startAnimation(fabClose);
fab_logout.startAnimation(fabClose);
fab_menu.startAnimation(fabAnticlockwise);
fab_balance.setClickable(false);
fab_logout.setClickable(false);
handler.postDelayed(new Runnable() {
#Override
public void run() {
t1.setVisibility(View.INVISIBLE);
t2.setVisibility(View.INVISIBLE);
t3.setVisibility(View.INVISIBLE);
}
},200);
isOpen = false;
}
else
{
fab_order.startAnimation(fabOpen);
fab_balance.startAnimation(fabOpen);
fab_logout.startAnimation(fabOpen);
fab_menu.startAnimation(fabClockwise);
fab_balance.setClickable(true);
fab_logout.setClickable(true);
isOpen = true;
handler.postDelayed(new Runnable() {
#Override
public void run() {
t1.setVisibility(View.VISIBLE);
t2.setVisibility(View.VISIBLE);
t3.setVisibility(View.VISIBLE);
}
},200);
}
}
});
fab_order.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
status = helper.checkUserStatus(helper.getUser());
if(!connectionDetector.isConnected()) {
Toast.makeText(HomeActivity.this, "Check your internet connection !!!", Toast.LENGTH_LONG).show();
return;
}
else if(!status) {
Toast t1 = Toast.makeText(HomeActivity.this, "Access Denied !!!", Toast.LENGTH_LONG);
Toast t2 = Toast.makeText(HomeActivity.this, "Please contact: Ayaz Handloom Store", Toast.LENGTH_LONG);
t1.setGravity(Gravity.CENTER,0,0);
t1.show();
t2.setGravity(Gravity.CENTER,0,0);
t2.show();
return;
}
else {
Intent newOrder = new Intent(HomeActivity.this, NewOrderActivity.class);
startActivity(newOrder);
finish();
}
}
});
fab_balance.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent balance = new Intent(HomeActivity.this,BalanceActivity.class);
startActivity(balance);
finish();
}
});
fab_logout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent logout = new Intent(HomeActivity.this,MainActivity.class);
helper.logout();
Toast.makeText(HomeActivity.this, "Logout success !!!", Toast.LENGTH_LONG).show();
startActivity(logout);
finish();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu,menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId())
{
case R.id.edit_profile:
break;
case R.id.change_password:
break;
case R.id.settings:
break;
case R.id.logout:
DialogInterface.OnClickListener dialogBox = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which){
case DialogInterface.BUTTON_POSITIVE:
Intent logout = new Intent(HomeActivity.this,MainActivity.class);
helper.logout();
Toast.makeText(HomeActivity.this, "Logout success !!!", Toast.LENGTH_LONG).show();
startActivity(logout);
finish();
break;
case DialogInterface.BUTTON_NEGATIVE:
Toast cancel = Toast.makeText(HomeActivity.this, "Request cancelled !!!", Toast.LENGTH_SHORT);
cancel.setGravity(Gravity.CENTER,0,0);
cancel.show();
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(HomeActivity.this);
builder.setMessage("Are you sure to logout?").setPositiveButton("Yes", dialogBox).setNegativeButton("No", dialogBox).show();
break;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(GravityCompat.START))
drawerLayout.closeDrawer(GravityCompat.START);
else {
if (!isUserClickedBackButton) {
Toast.makeText(this, "Press back key again for Main Page !!!", Toast.LENGTH_LONG).show();
isUserClickedBackButton = true;
handler.postDelayed(new Runnable() {
#Override
public void run() {
isUserClickedBackButton = false;
}
}, 3000);
} else {
Intent back = new Intent(HomeActivity.this, MainActivity.class);
startActivity(back);
finish();
}
}
}
}
If i delete XML code which is inside DrawerLayout, then it works fine.
you forgot to add drawerLayout.addDrawerListener(toggle); before toggle.syncState();
I am trying to create an array of ImageView controls and add drawable resources to it. I am getting
Caused by: java.lang.NullPointerException: Attempt to invoke virtual
method 'void android.widget.ImageView.setBackgroundResource(int)' on a
null object reference
Here is the code:
public class MultipleChoice extends ActionBarActivity {
TextView Left;
TextView Operator;
TextView Right;
TextView GameTimer;
TextView CorrectAnswers;
ImageView imageView[] = new ImageView[11];
int imageViewNumber;
Button btnStart;
int intLeft;
int intOperator;
int intRight;
int intCorrectAnswer;
int intCorrectAnswers;
String strCorrectAnswer;
CountDownTimer problemtimer = new CountDownTimer(10000,1000) {
#Override
public void onTick(long millisUntilFinished) {
}
#Override
public void onFinish() {
NextProblem();
}
};
CountDownTimer gametimer = new CountDownTimer(60000,1000) {
#Override
public void onTick(long millisUntilFinished) {
GameTimer.setText("Time Left: " + millisUntilFinished / 1000);
}
#Override
public void onFinish() {
problemtimer.cancel();
gametimer.cancel();
GameTimer.setText("Time Left: 0");
btnStart.setEnabled(true);
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_multiple_choice);
SetStartupValues();
}
private void SetStartupValues(){
Left = (TextView) findViewById(R.id.Left);
Operator = (TextView) findViewById(R.id.Operator);
Right = (TextView) findViewById(R.id.Right);
GameTimer = (TextView) findViewById(R.id.Timeleft);
CorrectAnswers = (TextView) findViewById(R.id.CorrectAnswers);
btnStart = (Button) findViewById(R.id.btnStart);
Left.setText("");
Operator.setText("");
Right.setText("");
GameTimer.setText("Time Left: 60");
CorrectAnswers.setText("Correct: 0");
intCorrectAnswers = 0;
}
#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) {
// 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);
}
public void btnStart_Click(View view) {
// Do something in response to button click
SetStartupValues();
NextProblem();
gametimer.start();
btnStart.setEnabled(false);
}
public void NextProblem(){
intLeft = new Random().nextInt(100);
intRight= new Random().nextInt(100);
intOperator= new Random().nextInt(3);
Left.setText(String.valueOf(intLeft));
Right.setText(String.valueOf(intRight));
imageViewNumber=0;
switch(intOperator){
case 0:
Operator.setText("+");
intCorrectAnswer = intLeft + intRight;
break;
case 1:
Operator.setText("-");
intCorrectAnswer=intLeft-intRight;
break;
case 2:
Operator.setText("X");
intCorrectAnswer=intLeft*intRight;
break;
}
strCorrectAnswer = String.valueOf(intCorrectAnswer);
GetNumbers(strCorrectAnswer);
problemtimer.start();
}
private void GetNumbers(String strNumber){
LinearLayout ll = (LinearLayout)findViewById(R.id.linearLayout1);
int L = strNumber.length();
String c;
for (int i = 0;i<L-1;i++){
c=strNumber.substring(i,i+1);
switch (c){
case "1":
imageView[imageViewNumber].setBackgroundResource(R.drawable.one);
ll.addView(imageView[imageViewNumber]);
break;
case "2":
imageView[imageViewNumber].setBackgroundResource(R.drawable.two);
ll.addView(imageView[imageViewNumber]);
break;
case "3":
imageView[imageViewNumber].setBackgroundResource(R.drawable.three);
ll.addView(imageView[imageViewNumber]);
break;
case "4":
imageView[imageViewNumber].setBackgroundResource(R.drawable.four);
ll.addView(imageView[imageViewNumber]);
break;
case "5":
imageView[imageViewNumber].setBackgroundResource(R.drawable.five);
ll.addView(imageView[imageViewNumber]);
break;
case "6":
imageView[imageViewNumber].setBackgroundResource(R.drawable.six);
ll.addView(imageView[imageViewNumber]);
break;
case "7":
imageView[imageViewNumber].setBackgroundResource(R.drawable.seven);
ll.addView(imageView[imageViewNumber]);
break;
case "8":
imageView[imageViewNumber].setBackgroundResource(R.drawable.eight);
ll.addView(imageView[imageViewNumber]);
break;
case "9":
imageView[imageViewNumber].setBackgroundResource(R.drawable.nine);
ll.addView(imageView[imageViewNumber]);
break;
case "0":
imageView[imageViewNumber].setBackgroundResource(R.drawable.zero);
ll.addView(imageView[imageViewNumber]);
break;
}
}
}
The error occurs in the Switch statement on the lines like
imageView[imageViewNumber].setBackgroundResource(R.drawable.zero);
What am I doing wrong?
Here is my Layout file
<RelativeLayout 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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MultipleChoice"
android:minWidth="30dp"
android:focusableInTouchMode="false">
<TextView android:text="#string/LeftText" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/Left"
android:layout_below="#+id/Timeleft"
android:layout_toLeftOf="#+id/Operator"
android:layout_toStartOf="#+id/Operator" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/OperatorText"
android:id="#+id/Operator"
android:layout_below="#+id/Timeleft"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/RightText"
android:id="#+id/Right"
android:layout_below="#+id/Timeleft"
android:layout_toRightOf="#+id/Operator"
android:layout_toEndOf="#+id/Operator" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/StartButton"
android:id="#+id/btnStart"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:onClick="btnStart_Click"
android:enabled="true"
android:focusable="false" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/TimeLeft"
android:id="#+id/Timeleft"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Correct: 0"
android:id="#+id/CorrectAnswers"
android:layout_alignTop="#+id/Timeleft"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/LinearContainer"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:baselineAligned="false">
<LinearLayout
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/linearLayout1"
android:layout_weight="1"
android:gravity="center_horizontal">
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:id="#+id/linearLayout2"
android:gravity="center_horizontal">
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:id="#+id/linearLayout3"
android:gravity="center_horizontal">
</LinearLayout>
</LinearLayout>
</RelativeLayout>
You dont have objects in your "imageView" array.
Initialize it with values:
for(int i = 0; i < imageView.lenght; i++) imageView[i] = new ImageView(context);
So you can use then properly.
Help me out to show Actionbar menu item on the Top of the Actionbar. Without showing on overflow drop down menulist.kindly give me a suggestion to do like that?
Use this in your activity
ActionBar actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(false);
LayoutParams lp = new LayoutParams(
android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
android.view.ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.RIGHT
| Gravity.CENTER_VERTICAL);
View customNav = LayoutInflater.from(this).inflate(R.layout.img, null);
EditText et = (EditText) customNav.findViewById(R.id.et);
temppaths = new ArrayList<String>();
Button iv = (Button) customNav.findViewById(R.id.iv);
iv.setClickable(true);
iv.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
});
actionBar.setCustomView(customNav, lp);
actionBar.setDisplayShowCustomEnabled(true);
and xmlLayout name it img.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:orientation="horizontal"
android:layout_height="wrap_content"
android:gravity="right" >
<EditText android:id="#+id/et"
android:layout_width="250dp"
android:layout_height="match_parent"
android:layout_marginRight="20dp"
android:gravity="center"
android:layout_gravity="right"
android:hint="info#xxxxxx, 1800xxxxx"
android:background="#FF8000" />
<Button
android:id="#+id/iv"
android:layout_gravity="right"
android:layout_width="150dp"
android:layout_height="match_parent"
android:layout_marginRight="20dp"
android:text="Search"
android:background="#FF8000" />
</LinearLayout >
okk then
add these methods in your activity
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu.add(0, 0, 0, "LogOut").setShortcut('0', 'o')
.setIcon(android.R.drawable.ic_menu_edit);
menu.add(0, 1, 0, "Save").setShortcut('1', 's')
.setIcon(android.R.drawable.ic_menu_save);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case 0:
Toast.makeText(getApplicationContext(), "Log out clicked", 0).show();
// save();
// showNewOrOpenDialog();
break;
case 1:
Toast.makeText(getApplicationContext(), "Save", 0).show();
// save();
break;
}
return false;
}
I have used fragments
activity_fragment_demo.xml
<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:orientation="vertical"
tools:context=".FragmentDemo" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Button" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Button" />
</LinearLayout>
<LinearLayout
android:id="#+id/simple_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
</LinearLayout>
</LinearLayout>
</LinearLayout>
FragmentDemo.java
public class FragmentDemo extends FragmentActivity implements OnClickListener {
Button b1, b2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fragment_demo);
b1 = (Button) findViewById(R.id.button1);
b2 = (Button) findViewById(R.id.button2);
b1.setOnClickListener(this);
b2.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.fragment_demo, menu);
return true;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.button1:
addFragment(new F1(this), false,
FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
break;
case R.id.button2:
addFragment(new F2(this), false,
FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
break;
default:
break;
}
}
void addFragment(Fragment fragment, boolean addToBackStack, int transition) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.simple_fragment, fragment);
ft.setTransition(transition);
if (addToBackStack)
ft.addToBackStack(null);
ft.commit();
}
}
F1.java
public class F1 extends Fragment {
Context c;
View v;
public F1(FragmentDemo fragmentDemo) {
// TODO Auto-generated constructor stub
this.c = fragmentDemo;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
v = inflater.inflate(R.layout.f1, container, false);
return v;
}
}
F2.java
public class F2 extends Fragment {
Context c;
View v;
public F2(FragmentDemo fragmentDemo) {
// TODO Auto-generated constructor stub
this.c = fragmentDemo;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
v = inflater.inflate(R.layout.f2, container, false);
return v;
}
}
OUTPUT SCREEN: -- > WHEN I CLICK BUtton on lefthand side
Similarly for next button
Now HOW CAN I Merge the thow buttons like below
Using fragments i have used .....
If i click on button once Activity-A1 must display in button
below .....
similarly If i click on button again Activity-A2 must display
below
Then if i click on third time ...... Activity-A1 must display
again
A Boolean nature of single button that repeats its cycle !
How to achieve this !
There are many ways to do this but here is a simple solution.
First change activity_fragment_demo.xml
<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:orientation="vertical"
tools:context=".FragmentDemo" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal">
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
android:visibility="gone"/>
</FrameLayout>
<LinearLayout
android:id="#+id/simple_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
</LinearLayout>
</LinearLayout>
</LinearLayout>
next in FragmentDemo.java just change your onClick method like this:
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.button1:
addFragment(new F1(this), false,
FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
b1.setVisibility(View.GONE);
b2.setVisibility(View.VISIBLE);
break;
case R.id.button2:
addFragment(new F2(this), false,
FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
b2.setVisibility(View.GONE);
b1.setVisibility(View.VISIBLE);
break;
default:
break;
}
}
Your Activity could keep track of the state with a boolean. For example like this:
private boolean state = false;
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
state = !state;
if (state) {
addFragment(new F2(this), false,
FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
} else {
addFragment(new F1(this), false,
FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
}
break;
default:
break;
}
}
I create custom view for action bar: action_bar_bets.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="right"
android:weightSum="2"
android:orientation="horizontal" >
<ImageButton
android:id="#+id/actionBarProfile"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:paddingRight="10dp"
android:src="#drawable/ic_action_user" />
<ImageButton
android:id="#+id/actionBarBets"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:paddingRight="10dp"
android:src="#drawable/ic_action_betslip" />
</LinearLayout>
here is my menu: action_bar.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="#+id/mybetsCount"
android:actionLayout="#layout/action_bar_bets"
android:showAsAction="always"/>
</menu>
I create action bar in code:
ActionBar actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayUseLogoEnabled(false);
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowCustomEnabled(true);
View view = getLayoutInflater().inflate(R.layout.action_bar_bets, null);
actionBar.setCustomView(view)
I tried set OnClickListener to ImageButtons:
like this:
ImageButton profile = (ImageButton) view.findViewById(R.id.actionBarProfile);
profile.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Profile", Toast.LENGTH_SHORT).show();
}
});
and like this:
actionBar.getCustomView().setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.actionBarProfile:
Toast.makeText(getApplicationContext(), "Profile", Toast.LENGTH_SHORT).show();
break;
default:
break;
}
}
});
But nothing happened
Can you help me to fix this problem?
ADD
Also in this class i have ListNavigation
PackageManager pm = getPackageManager();
String label;
try {
ActivityInfo activityInfo = pm.getActivityInfo(getComponentName(),
0);
label = activityInfo.loadLabel(pm).toString();
} catch (NameNotFoundException e) {
label = null;
e.printStackTrace();
}
String[] navigations = { label, "Sports", "Profile" };
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
getBaseContext(), R.layout.custom_spinner_title_bar,
android.R.id.text1, navigations);
adapter.setDropDownViewResource(R.layout.custom_spinner_title_bar);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
ActionBar.OnNavigationListener navigationListener = new OnNavigationListener() {
#Override
public boolean onNavigationItemSelected(int itemPosition,
long itemId) {
switch (itemPosition) {
case 1:
Intent intent = new Intent(getApplicationContext(),
MainActivity.class);
startActivity(intent);
break;
case 2:
intent = new Intent(getApplicationContext(),
Activity_profile.class);
startActivity(intent);
break;
default:
break;
}
return false;
}
};
actionBar.setListNavigationCallbacks(adapter, navigationListener);
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.action_bar, menu);
return true;
}
im not sure where you initialize your buttons, but when it is in something like onCreate() then replace
ImageButton profile = (ImageButton) view.findViewById(R.id.actionBarProfile);
with
ImageButton profile = (ImageButton) findViewById(R.id.actionBarProfile);
Try this. This is example with a Switch but it's the same way for other component
getMenuInflater().inflate(R.menu.export, menu);
MenuItem item = menu.findItem(R.id.myswitch);
Switch switchOnActionBar = (Switch)item.getActionView().findViewById(R.id.switchForActionBar);
switchOnActionBar.setOnCheckedChangeListener(this);
SwitchForActionBar is in switch_layout.xml :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:layout_gravity="center_vertical"
android:gravity="center_vertical">
<Switch
android:id="#+id/switchForActionBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOff="Manuel"
android:textOn="Auto"
android:gravity="center_vertical"
android:thumb="#drawable/switch_thumb"
android:textColor="#color/white"
android:textColorHint="#color/white"
android:background="#android:color/transparent"
android:layout_marginRight="10dp"/>
</RelativeLayout>
And this is the menu layout
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="#+id/myswitch"
android:title=""
android:checkable="true"
android:showAsAction="always"
android:actionLayout="#layout/switch_layout"
/>
</menu>
try ontouchlistener for imagebutton :
Change
setOnClickListener(new OnClickListener()
to :
setOnTouchListener(new OnTouchListener()
I found where i has error.
LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, Gravity.RIGHT | Gravity.CENTER_VERTICAL);
actionBar.setCustomView(view, lp);
and delete this code:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.action_bar, menu);
return true;
}
My navigation list overlaps the buttons
Thank you all for the help