fragment - navigation drawer - app stopped error - android-fragments

Greeting
When I click on the camera text, the app shows an error said "The application has stopped". How it can be fixed?
MaingActivity.java
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
CameraFragment cameraFragment = new CameraFragment();
FragmentManager manager= getSupportFragmentManager();
manager.beginTransaction().replace(
R.id.relativelayout_for_fragment,
cameraFragment,
cameraFragment.getTag()
).commit();
} else if (id == R.id.nav_gallery) {
Toast.makeText(this,"Gallary",Toast.LENGTH_SHORT).show();
} else if (id == R.id.nav_gallery) {
} 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;
}

I have found it
Select contant_main.xml => click on icon refer Constrains
The code will be as the following
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.example.shakeralmoosa.nav1.MainActivity"
tools:showIn="#layout/app_bar_main"
android:id="#+id/mainLayout">
<RelativeLayout
android:layout_width="0dp"
android:layout_height="0dp"
tools:layout_constraintTop_creator="1"
tools:layout_constraintRight_creator="1"
tools:layout_constraintBottom_creator="1"
android:layout_marginStart="5dp"
app:layout_constraintBottom_toBottomOf="parent"
android:layout_marginEnd="5dp"
app:layout_constraintRight_toRightOf="parent"
android:layout_marginTop="4dp"
tools:layout_constraintLeft_creator="1"
android:layout_marginBottom="4dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp">
</RelativeLayout>
</android.support.constraint.ConstraintLayout>

Related

androidx.spinner onItemSelectedListener not working

Am trying to use a spinner in a layout. I can add and select items to the spinner but I cannot retrieve the selected item. This is the main activity:
class pageNewPurchaseOrder : AppCompatActivity() {
lateinit var spinnerVendorX: androidx.appcompat.widget.AppCompatSpinner
var spinnerArray: java.util.ArrayList<CharSequence> = ArrayList<CharSequence>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_page_new_purchase_order)
setSupportActionBar(toolbar)
supportActionBar?.setDisplayShowTitleEnabled(false)
spinnerVendorX = findViewById(R.id.spinnerVendorX)
spinnerVendorX.adapter = ArrayAdapter(this#pageNewPurchaseOrder, android.R.layout.simple_spinner_item, spinnerArray)
spinnerVendorX.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onNothingSelected(parent: AdapterView<*>?) {
}
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
Log.d("aaa", "This code is not running!")
}
}
}
}
This is the layout activity
<?xml version="1.0" encoding="utf-8"?>
<androidx.core.widget.NestedScrollView 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:background="?attr/colorPrimary"
android:fillViewport="true"
android:focusable="true"
android:focusableInTouchMode="true"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context=".pageNewPurchaseOrder"
tools:showIn="#layout/activity_page_new_purchase_order">
<androidx.appcompat.widget.AppCompatSpinner
android:padding="10dp"
android:background="#drawable/bgselect"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="#+id/lbl2"
android:id="#+id/spinnerVendorX" />
</androidx.core.widget.NestedScrollView>
Am getting result this on the logcat when I select an item: E/ViewRootImpl(31835): sendUserActionEvent() mView == null.I get tj=he same results even when I use <Spinner instead of <androidx.appcompat.widget.AppCompatSpinner
User must have to add data in the ArrayList. Here, you are initialising arrayList and set it but not adding data in ArrayList. Please add data in ArrayList then try it. Thank you.

Image capture and upload inside a fragment in kotlin

THIS IS MY XML
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context=".MakeComplaint.Category_Description"
android:background="#drawable/fragmentgradient_bg">
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/heading_constraint"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
tools:layout_editor_absoluteX="17dp">
<ImageView
android:id="#+id/backToHistory"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:paddingHorizontal="20dp"
android:layout_weight="2"
android:src="#drawable/ic_backarrow"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintRight_toLeftOf="#+id/location_title"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/location_title"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:paddingHorizontal="20dp"
android:fontFamily="#font/pathway_gothic_one"
android:gravity="center"
android:textSize="40sp"
android:text="Further Details"
app:layout_constraintHorizontal_bias="0.35"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toRightOf="#+id/backToHistory"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
<androidx.cardview.widget.CardView
android:id="#+id/details_card"
android:layout_width="0dp"
android:layout_height="0dp"
android:elevation="#dimen/card_spacing"
app:cardUseCompatPadding="true"
app:layout_constraintTop_toBottomOf="#+id/heading_constraint"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:cardCornerRadius="#dimen/card_spacing"
>
<ScrollView
android:id="#+id/scroll"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true">
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/inner_constraint"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="#dimen/card_spacing">
<TextView
android:id="#+id/guide"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="#font/pathway_gothic_one"
android:gravity="left"
android:text="Please enter any further details you would like to add:"
android:textSize="20sp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/description_text_input"
style="#style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
app:boxStrokeColor="#color/teal"
app:boxStrokeWidth="#dimen/card_spacing"
app:counterEnabled="true"
app:counterMaxLength="500"
android:hint="Additional Notes"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="#id/guide"
app:prefixTextColor="#color/colorPrimaryDark"
android:outlineAmbientShadowColor="#color/teal"
android:outlineSpotShadowColor="#color/teal"
android:scrollbarAlwaysDrawHorizontalTrack="true"
app:layout_constraintBaseline_creator="#android:integer/config_longAnimTime"
>
<com.google.android.material.textfield.TextInputEditText
android:id="#+id/description"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textCapSentences|textMultiLine"
android:maxLength="500"
/>
</com.google.android.material.textfield.TextInputLayout>
<!--ImageView where image will be set-->
<ImageView
android:id="#+id/display_image"
android:scaleType="centerCrop"
android:layout_width="250dp"
android:layout_height="250dp"
android:adjustViewBounds="true"
app:layout_constraintTop_toBottomOf="#+id/description_text_input"
app:layout_constraintBottom_toTopOf="#+id/FAB_buttons"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintLeft_toLeftOf="parent"/>
<androidx.appcompat.widget.LinearLayoutCompat
android:id="#+id/FAB_buttons"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintTop_toBottomOf="#+id/description_text_input"
app:layout_constraintRight_toRightOf="parent"
android:layout_marginVertical="5dp">
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/camera"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="16dp"
app:backgroundTint="#color/teal"
android:layout_marginHorizontal="#dimen/card_spacing"
android:src="#android:drawable/ic_menu_camera"
app:layout_constraintRight_toLeftOf="#+id/camera"
app:layout_constraintTop_toBottomOf="#+id/name_text_input"
/>
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/upload"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="16dp"
app:backgroundTint="#color/teal"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="#+id/name_text_input"
android:src="#android:drawable/ic_menu_gallery"
/>
</androidx.appcompat.widget.LinearLayoutCompat>
<com.google.android.material.button.MaterialButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Make Complaint"
app:layout_constraintTop_toBottomOf="#+id/FAB_buttons"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:backgroundTint="#color/teal"
/>
</androidx.constraintlayout.widget.ConstraintLayout>
</ScrollView>
</androidx.cardview.widget.CardView>
</androidx.constraintlayout.widget.ConstraintLayout>```
**THIS IS MY KOTLIN FILE**
package com.example.atry.MakeComplaint
class Category_Description : Fragment() {
private val ALL_PERMISSIONS_RESULT = 107
private val IMAGE_RESULT = 200
private val REQUEST_IMAGE_CAPTURE = 12345
var mBitmap: Bitmap? = null
val permission = 1
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val v = inflater.inflate(com.example.atry.R.layout.fragment_category__description, container, false)
val camera_FAB: View = v.findViewById(com.example.atry.R.id.camera)
val upload_FAB: View = v.findViewById(com.example.atry.R.id.upload)
val imageView = v.findViewById<ImageView>(com.example.atry.R.id.display_image)
upload_FAB.setOnClickListener {
pickImageFromGallery()
}
camera_FAB.setOnClickListener{
val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
val frag = this
/** Pass your fragment reference **/
frag.startActivityForResult(
intent,
REQUEST_IMAGE_CAPTURE
) // REQUEST_IMAGE_CAPTURE = 12345
}
fun hasPermissionInManifest(context: Context, permissionName: String): Boolean {
val packageName = context.packageName
try {
val packageInfo = context.packageManager
.getPackageInfo(packageName, PackageManager.GET_PERMISSIONS)
val declaredPermisisons = packageInfo.requestedPermissions
if (declaredPermisisons != null && declaredPermisisons.size > 0) {
for (p in declaredPermisisons) {
if (p == permissionName) {
return true
}
}
}
} catch (e: PackageManager.NameNotFoundException) {
}
return false
}
v.backToHistory.setOnClickListener {
backFragment()
}
// Inflate the layout for this fragment
return v
}
private fun pickImageFromGallery() {
//Intent to pick image
val intent = Intent(Intent.ACTION_PICK)
intent.type = "image/*"
startActivityForResult(intent, IMAGE_PICK_CODE)
}
companion object {
//image pick code
private val IMAGE_PICK_CODE = 1000;
//Permission code
private val PERMISSION_CODE = 1001;
}
private fun backFragment() {
val manager = (context as AppCompatActivity).supportFragmentManager
manager.popBackStackImmediate()
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == Activity.RESULT_OK && data !=null) {
if (requestCode == REQUEST_IMAGE_CAPTURE || requestCode== IMAGE_PICK_CODE) {
// Do something with imagePath
val extras = data.getExtras()
val photo = extras.get("data") as Bitmap
val imageView = view!!.findViewById<ImageView>(com.example.atry.R.id.display_image)
imageView.setImageBitmap(photo)
// CALL THIS METHOD TO GET THE URI FROM THE BITMAP
var selectedImage = activity.let { getImageUri( it!!,photo) }
val realPath = selectedImage.let { getRealPathFromURI(it) }
selectedImage = Uri.parse(realPath)
}
}
super.onActivityResult(requestCode, resultCode, data)
}
fun getImageUri(inContext: Context, inImage: Bitmap): Uri {
val bytes = ByteArrayOutputStream()
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes)
val path =
MediaStore.Images.Media.insertImage(inContext.contentResolver, inImage, "Title", null)
return Uri.parse(path)
}
fun getRealPathFromURI(contentUri: Uri): String {
var cursor: Cursor? = null
try {
val proj = arrayOf(MediaStore.Images.Media.DATA)
cursor = getActivity()?.getContentResolver()?.query(contentUri, proj, null, null, null)
val column_index = cursor!!.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)
cursor!!.moveToFirst()
return cursor!!.getString(column_index)
} finally {
if (cursor != null) {
cursor!!.close()
}
}
}
}```
For capturing the image everything works fine until the screen appears where I click on the tick to approve that the picture is okay...but then I am unable to view anything on the ImageView.
For the upload button when I am on the screen that allows me to select the picture ...when i click on it the app crashes and gives me the following error: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object android.os.Bundle.get(java.lang.String)' on a null object reference
I have searched the internet for days and couldn't find a proper solution to this. I would appreciate it if anyone could find me a solution to this.
URI of the selected image is not returned in Intent extras, but in the data of intent. You can get the selected image's URI as follows.
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == Activity.RESULT_OK && data !=null) {
if (requestCode == REQUEST_IMAGE_CAPTURE || requestCode== IMAGE_PICK_CODE) {
// Get image URI From intent
var imageUri = data.data
// do something with the image URI
your_image_view.setImageURI(imageUri)
}
}
super.onActivityResult(requestCode, resultCode, data)
}

listview inside scrollview not working on android version lower than API 18

ListView inside ScrollView works perfectly on android API greater than 18 but, with lower than API 18 app crash showing java.lang.NullPointerException in line
listItem.measure(0, 0); on MyUtils.java
MyUtils.java
public static void setListViewHeightBasedOnChildren(ExpandableListView listView) {
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null) {
// pre-condition
return;
}
int totalHeight = 0;
for (int i = 0; i < listAdapter.getCount(); i++) {
View listItem = listAdapter.getView(i, null, listView);
listItem.measure(0, 0);
totalHeight += listItem.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
listView.setLayoutParams(params);
listView.requestLayout();
}
fragment_list.xml
<FrameLayout 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"
tools:context="sportsnewsforcrazysportpepllatestnewsjstwaao.com.sportsnews.fragments.Frag_List">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.android.volley.toolbox.NetworkImageView
android:id="#+id/networkImageView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:background="#color/divider"
android:minHeight="150dp"/>
<ExpandableListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/expandableListView"
android:scrollbars="none"
android:background="#color/app_background"
android:childDivider="#color/app_background"/>
</LinearLayout>
</ScrollView>
Fragment_list.java
adapter = new ExpandableListViewAdapter(getActivity() , dataList);
expandableListView.setAdapter(adapter);
MyUtils.setListViewHeightBasedOnChildren(expandableListView);
expandableListView.setOnGroupClickListener(this);
expandableListView.setOnChildClickListener(this);
In my app,if listview item layout's root view is RelativeLayout,it will cause this crash.Because in api 18 RelativeLayout source code
if(mLayoutParams.width >= 0) {
width = Math.max(width, mLayoutParams.width);
}
and in api >=19 RelativeLayout source code
if(mLayoutParams != null && mLayoutParams.width >= 0) {
width = Math.max(width, mLayoutParams.width);
}
the mLayoutParams maybe null if you inflate item view in this method:
contentView = (ViewGroup) LayoutInflater.
rom(context).inflate(R.layout.select_text_oprate_window, null);
So,you can use this method:
contentView = (ViewGroup)
LayoutInflater.from(context).inflate(R.layout.select_text_oprate_window, parent,false);
Also you can change item layout's root view to LinearLayout.

Navigation Drawer opens to different fragments

I am a beginner when it comes to Android. I have spent hours reading tutorials, watching videos, and combing through stackoverflow trying to figure this out. Even with all the online resources available , I still can't figure this out.
I want my list view always on the main screen, but when I swipe I want the navigation drawer to slide in and display a different fragment depending on which item in the list view has been selected. For example if the user selected 'account', when they slide from the right the account fragment would display.
I've left in 'navList' and 'nav2List' for testing, but I would like these to be fragments.
XML
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<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=".MainActivity">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/bankMenu"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
</ListView>
</RelativeLayout>
<!-- Side navigation drawer UI -->
<ListView
android:id="#+id/navList"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="right"
android:background="#ffeeeeee"/>
<ListView
android:id="#+id/nav2List"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="right"
android:background="#ffeeeeee"/>
</android.support.v4.widget.DrawerLayout>
JAVA
public class MainActivity extends AppCompatActivity {
private ListView menu;
private ListView mDrawerList;
private ListView secondDrawerList;
private ArrayAdapter<String> mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
menu = (ListView) findViewById(R.id.bankMenu);
mDrawerList = (ListView)findViewById(R.id.navList);
secondDrawerList = (ListView)findViewById(R.id.nav2List);
addBankingListItems(); // populate the banking items list
menu.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
final int position, long id) {
// ListView Clicked item index
int itemPosition = position;
// ListView Clicked item value
String itemValue = (String) menu.getItemAtPosition(position);
// Show Alert
Toast.makeText(getApplicationContext(),
"Position :" + itemPosition + " ListItem : " + itemValue, Toast.LENGTH_LONG)
.show();
if (itemPosition < 4) { // TESTING FUNCTIONALITY
addDrawerItems();
} else {
addSecondDrawerItems();
}
}
});
}
---EDIT---
This issue has been resolved.
In the xml file, i changed the two ListViews to a RelativeView.
<RelativeLayout
android:id="#+id/frame_to_be_replaced"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="right"
android:layout_below="#+id/topRL"
android:background="#ffeeeeee">
</RelativeLayout>
In the MainActivity, I created a fragment manager, then after my switch statement, i replaced the frame with the required one. Hope this can help someone, send me a pm for more info.
FragmentManager fragmentManager = getFragmentManager();
switch (itemPosition) {
case 0:
fragment = MyFrag1.newInstance("", ""); // fragment declared above
break;
case 1:
fragment = MyFrag2.newInstance("", "");
break;
case 2: etc....
fragmentManager.beginTransaction()
.replace(R.id.frame_to_be_replaced, fragment)
.commit();

Android popup won't dismiss

I am trying to implement a popup in my application but it won't dismiss. The Popup is supposed to open when I click on a Plus button, and this works. However, it is supposed to close when I click on the Cancel button in popup layout but it doesn't. why?
Popup layout (tempo_popup.xml):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<EditText
android:id="#+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="number" >
<requestFocus />
</EditText>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_weight="1" >
<Button
android:id="#+id/confirmtempo"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/Confirm" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_weight="1" >
<Button
android:id="#+id/canceltempo"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/Cancel" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
Java code:
public class MetronomeActivity extends Activity{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_metronome);
final Button plus = (Button) findViewById(R.id.tempop);
final Button minus = (Button) findViewById(R.id.tempom);
final Button confirm_tempo = (Button) findViewById(R.id.confirmtempo);
plus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final LayoutInflater inflater = (LayoutInflater) getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View pop = inflater.inflate(R.layout.tempo_popup, null, false);
final PopupWindow pw = new PopupWindow(
inflater.inflate(R.layout.tempo_popup, null, false),
250, 150, true);
// The code below assumes that the root container has an id called 'main'
pw.showAtLocation(plus, Gravity.CENTER, 0, 0);
Button cancel_tempo = (Button) pop.findViewById(R.id.canceltempo);
cancel_tempo.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i("Begin1", "POPUP CANCEL");
pw.dismiss();
}
});
}
});
}
}
Damn it! Replace single line of code, it will work like charm.
Instead:
PopupWindow popUpWindow = new PopupWindow(inflater.inflate(R.layout.tempo_popup, null, false),250, 150, true);
Use:
View view = inflater.inflate(R.layout.tempo_popup, null, false);
PopupWindow popUpWindow = new PopupWindow(view, 250, 150, true);
Does the Popup cancel log get printed? Otherwise this might help:
Android popup window dismissal

Resources