showPopupMenu method not working when clickng on ImageView - android

I have a popup menu inside every item on a listview. When you click the imageview to the left (settings img with 3 dots) a popup menu should showup. however, I'm getting error
Could not find a method showPopupMenu(View) in the activity class android.app.Application for onClick handler on view class android.widget.ImageView with id 'settings_img'
does anyone know what this error is. it is obvious that can't find the method, but is it because it can't find the class/view? if so how can I fix it? thanks
main_activity
package com.example.george.hostscanmenus;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
List hostList;
ArrayAdapter<String> hostAdapter;
PopupMenu popup;
String subnet = "192.168.10.";
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
hostList = new ArrayList<String>();
//populating host addresses
for(int i = 0; i < 255; i++) {
hostList.add(subnet+i +"-aa:bb:00:cc:33:ee");
}
//inflating adapter
listView = (ListView) findViewById(R.id.scan_list);
hostAdapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.host_item, R.id.ip_address, hostList);
listView.setAdapter(hostAdapter);
}
/* code for popup menu in listview */
public void showPopupMenu(View v) {
popup = new PopupMenu(this, v);
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.change_icon:
Toast.makeText(getApplicationContext(), menuItem.getTitle(), Toast.LENGTH_SHORT).show();
return true;
case R.id.notifications:
Toast.makeText(getApplicationContext(), menuItem.getTitle(), Toast.LENGTH_SHORT).show();
return true;
default:
return MainActivity.super.onContextItemSelected(menuItem);
}
}
});
MenuInflater inflater = popup.getMenuInflater();
inflater.inflate(R.menu.host_menu, popup.getMenu());
popup.show();
}
}
array adapter
package com.example.george.hostscanmenus;
import android.content.Context;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created by george on 8/11/17.
*/
public class HostAdapter extends ArrayAdapter<String> {
public HostAdapter(Context context, int num, ArrayList<String> allHost) {
super(context, 0, allHost);
}
#NonNull
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
String host = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.activity_main, parent, false);
}
// Lookup view for data population
ImageView nodeHostImgView = (ImageView) convertView.findViewById(R.id.host_icon);
TextView nodeIpTxtView = (TextView) convertView.findViewById(R.id.ip_address);
TextView nodeMacTxtView = (TextView) convertView.findViewById(R.id.mac_address);
ImageView nodeArrowImgView = (ImageView) convertView.findViewById(R.id.port_scan_arrow);
// Populate the data into the template view using the data object
nodeHostImgView.setImageResource(R.drawable.ic_computer_white_24dp);
nodeIpTxtView.setText(host.substring(0,host.indexOf("-")));
nodeMacTxtView.setText(host.substring(host.indexOf("-")));
nodeArrowImgView.setImageResource(R.drawable.ic_keyboard_arrow_right_white_24dp);
// Return the completed view to render on screen
return convertView;
}
}
main xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="#+id/scan_list_linear"
tools:context=".MainActivity">
<!-- labels for ip / mac addres list -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/list_label">
<TextView
android:id="#+id/host_port_label"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.20"
android:text="Host"
android:textSize="20dp"
android:textAlignment="center"
android:textColor="#color/colorAccent"/>
<TextView
android:id="#+id/ip_open_label"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.80"
android:textSize="20dp"
tools:text="IP / MAC"
android:paddingLeft="10dp"
android:textColor="#color/colorAccent"/>
<TextView
android:id="#+id/scan_label"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.20"
android:text="Scan"
android:textSize="20dp"
android:textAlignment="center"
android:textColor="#color/colorAccent"/>
</LinearLayout>
<!--Listview to display scan output-->
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/scan_list"/>
</LinearLayout>
list item xml
<?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="wrap_content"
android:orientation="horizontal">
<LinearLayout
android:id="#+id/text_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:id="#+id/settings_img"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="0.10"
android:padding="3dp"
android:src="#drawable/ic_action_more_vert"
android:onClick="showPopupMenu"/>
<ImageView
android:id="#+id/host_icon"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="0.20"
android:padding="5dp"
android:src="#drawable/ic_computer_white_24dp"/>
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.50"
android:orientation="vertical"
android:paddingLeft="0dp"
>
<TextView
android:id="#+id/ip_address"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="18dp"
tools:text="192.168.10.100"
/>
<TextView
android:id="#+id/mac_address"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="16dp"
tools:text="aa:bb:cc:00:11:22"
/>
</LinearLayout>
<ImageView
android:id="#+id/port_scan_arrow"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="0.20"
android:padding="5dp"
android:src="#drawable/ic_keyboard_arrow_right_white_24dp"/>
</LinearLayout>
</RelativeLayout>
menu xml
<!-- listview menu for host scan options eg:
change hostname, icon, notification etc -->
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<!-- Settings, should always be in the overflow -->
<item android:id="#+id/change_icon"
android:title="change icon"
/>
<item android:id="#+id/notifications"
android:title="set notification"
/>
</menu>

You should define your settings_img on your adapter getView and add a click listener for each element.
example:
ImageView settingsImgView = (ImageView) convertView.findViewById(R.id.settings_img);
settingsImgView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
context.showPopupMenu() //or popupmenu logic in here if you want
}
});

Usually, when it comes to the adapter, I pass the activity itself instead of the context. Then I pass the activity's context to super() and keep the activity in the field variable. That way I'm able to use all public methods of the parent activity.

Related

Item List Layout showing up in Android Studio, but not in Emulator

I am working on an Android App with a Recyclerview that contains a Listview. The problem is, that the Listview items are showing up in Android Studio, that there are no errors in the XML but still, the Listview items are not showing up on the Emulator or on a Real device. I checked the Layout for all kinds of problems - Size, Width, Layout Constraints -, but I couldn´t find any. As I am stuck here, I would kindly appreciate any help or hints from the community, thanks in advance.
The Activity:
package com.example.xxx;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.GradientDrawable;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupMenu;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import okhttp3.Credentials;
import static com.example.xxx.SimpleItemRecyclerViewAdapter.TAGG;
import static com.example.xxx.SimpleItemRecyclerViewAdapter.palNo;
/**
* An activity representing a single Main detail screen. This
* activity is only used on narrow width devices. On tablet-size devices,
* item details are presented side-by-side with a list of items
* in a {#link MainListActivity}.
*/
public final class ProductDetailActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener,
PopupMenu.OnMenuItemClickListener {
public Context context;
private RecyclerView recyclerView;
private StockBookingsRecyclerviewAdapter recyclerviewAdapter;
private RecyclerTouchListener touchListener;
public static final String TAG = "Barcode ist:" ;
public String bookingType = null;
public String itemNo = null;
public String ean = null;
public String quantity = null;
public String packageCode = null;
public String target = null;
public String source = null;
public Date date;
public String scannedCode = null;
public static final String Profile_Prefs = "Pro_File";
public static SharedPreferences profile;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_product_detail);
TextView titleBooking = findViewById(R.id.title_booking);
TextView typeBooking = findViewById(R.id.type_booking);
TextView nameBooking = findViewById(R.id.name_booking);
TextView dateBooking = findViewById(R.id.date_booking);
Toolbar toolbar = findViewById(R.id.toolbar);
LinearLayout linearLayout = findViewById(R.id.rowFGP);
String selectedItem =null;
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.mockdata, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
String basic = Credentials.basic("xxx", "xxx");
// Apply the adapter to the spinner
recyclerView = findViewById(R.id.recyclerview2);
recyclerviewAdapter = new StockBookingsRecyclerviewAdapter(this);
Intent newIntent = getIntent();
String receivedPalNo = newIntent.getStringExtra("palNo");
String receivedNo = newIntent.getStringExtra("no");
String receivedType = newIntent.getStringExtra("type");
String receivedRack = newIntent.getStringExtra("rack");
String receivedCountItems = newIntent.getStringExtra("count_items");
RestClient.getStockBookings(getApplicationContext(),recyclerviewAdapter,basic);
Log.d(TAGG,"Intent 1" + receivedPalNo);
Log.d(TAGG, "Intent 2" + receivedNo);
Log.d(TAGG, "Intent 3" + receivedType);
Log.d(TAGG,"Intent 4" + receivedRack);
Log.d(TAGG, "Intent 5" + receivedCountItems);
//use a GradientDrawable with only one color set, to make it a solid color
GradientDrawable border = new GradientDrawable();
border.setColor(0x00000000); //white background
border.setStroke(1, 0xFF000000); //black border with full opacity
final ArrayList<StockBookings> stockBookingList = new ArrayList<>();
recyclerviewAdapter. setBookingList((ArrayList<StockBookings>) stockBookingList);
recyclerView.setAdapter(recyclerviewAdapter);
touchListener = new RecyclerTouchListener(this,recyclerView);
StockBookingsRecyclerviewAdapter finalRecyclerviewAdapter = recyclerviewAdapter;
touchListener
.setClickable(new RecyclerTouchListener.OnRowClickListener() {
#Override
public void onRowClicked(int position) {
}
#Override
public void onIndependentViewClicked(int independentViewID, int position) {
}
})
.setSwipeOptionViews(R.id.delete_task)
.setSwipeable(R.id.rowFGP, R.id.rowBGP, new RecyclerTouchListener.OnSwipeOptionsClickListener() {
#Override
public void onSwipeOptionClicked(int viewID, int position) {
stockBookingList.remove(position);
finalRecyclerviewAdapter.setStockBookingList(stockBookingList);
}
});
}
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 void onBackPressed() {
Intent setIntent = new Intent(getApplicationContext(),MainListActivity.class);
startActivity(setIntent);
}
public boolean onMenuItemClick(MenuItem item) {
Toast.makeText(this, "Selected Item: " +item.getTitle(), Toast.LENGTH_SHORT).show();
switch (item.getItemId()) {
case R.id.search_item:
// do your code
return true;
case R.id.upload_item:
// do your code
return true;
case R.id.copy_item:
// do your code
return true;
/* case R.id.print_item:
// do your code
return true;*/
case R.id.share_item:
// do your code
return true;
/*case R.id.bookmark_item:
// do your code
return true;*/
default:
return false;
}
}
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
// An item was selected. You can retrieve the selected item using
// parent.getItemAtPosition(pos)
}
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
navigateUpTo(new Intent(this, MainListActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onResume() {
super.onResume();
recyclerView.addOnItemTouchListener(touchListener);
}
#Override
public void onPointerCaptureChanged(boolean hasCapture) {
}
}
The Activity XML:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="#+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="#dimen/_80sdp"
android:layout_marginBottom="12dp"
android:layout_weight="0.15"
android:background="#drawable/border_set"
android:orientation="horizontal"
app:layout_constraintBottom_toTopOf="#id/recyclerview2">
<LinearLayout
android:id="#+id/linearLayout2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/txt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="20dp"
android:text="#string/product_bookings"
android:textColor="#color/black"
android:textSize="#dimen/_20sdp"
android:textStyle="bold"
app:layout_constraintBottom_toTopOf="#+id/txt1"
app:layout_constraintEnd_toEndOf="#id/txt1" />
<TextView
android:id="#+id/txt2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:text="#string/nicht_uebertragen"
android:textColor="#color/black"
android:textSize="#dimen/_10sdp"
android:textStyle="bold"
app:layout_constraintBottom_toTopOf="#+id/txt1"
app:layout_constraintEnd_toEndOf="#id/txt1" />
</LinearLayout>
</LinearLayout>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerview2"
android:layout_width="match_parent"
android:layout_height="#dimen/_280sdp"
android:layout_weight="0.7"
tools:itemCount="7"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
app:layout_constraintTop_toBottomOf="#+id/linearLayout"
tools:listitem="#layout/product_item" />
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/constraintLayout"
android:layout_width="match_parent"
android:layout_height="#dimen/_110sdp"
android:layout_weight="0.15"
android:gravity="bottom"
android:padding="5dp"
app:layout_constraintTop_toBottomOf="#id/recyclerview2"
tools:layout_editor_absoluteX="0dp">
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/floating_action_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|right"
android:layout_margin="16dp"
android:layout_marginStart="5dp"
android:layout_marginTop="5dp"
android:contentDescription="#string/fab_content_desc"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/ic_add_circle_outline" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
The Product Item XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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="wrap_content"
android:background="#drawable/background_border"
android:orientation="vertical">
<LinearLayout
android:id="#+id/rowBGP"
android:background="#color/colorPrimaryDark"
android:layout_width="wrap_content"
android:layout_height="60dp"
android:layout_alignParentRight="true"
android:gravity="right"
android:orientation="horizontal">
<RelativeLayout
android:id="#+id/delete_task"
android:layout_width="50dp"
android:layout_height="match_parent"
android:clickable="true"
android:focusable="true"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerInParent="true"
android:gravity="center"
android:orientation="vertical">
<TextView
android:id="#+id/img_delete"
android:layout_width="50dp"
android:layout_marginTop="#dimen/_1sdp"
android:layout_height="59dp"
android:background="#color/light_red"
android:text="#string/edit_article"
android:textSize="12dp"
android:textStyle="bold|italic"
app:tint="#android:color/white" />
</LinearLayout>
</RelativeLayout>
</LinearLayout>
<LinearLayout
android:id="#+id/rowFGP"
android:layout_width="match_parent"
android:layout_height="60dp"
android:background="#android:color/white"
android:clickable="true"
android:elevation="4dp"
android:focusable="true"
android:orientation="horizontal"
android:layout_margin="1dp"
android:visibility="visible">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:foreground="?attr/selectableItemBackground">
<TextView
android:id="#+id/title_booking"
style="#style/TextAppearance.AppCompat.Medium"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="#dimen/_2sdp"
android:layout_marginBottom="32dp"
android:lines="1"
android:text="#string/product_bookings"
android:textFontWeight="900"
android:textSize="#dimen/_15sdp"
android:textStyle="bold|italic"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.888" />
<TextView
android:id="#+id/type_booking"
android:text="#string/booking_type"
style="#style/TextAppearance.AppCompat.Headline"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:textSize="#dimen/_10sdp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.265"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.615" />
<TextView
android:id="#+id/name_booking"
android:text="#string/name_booking"
style="#style/TextAppearance.AppCompat.Headline"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="24dp"
android:textSize="#dimen/_15sdp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.265"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.615" />
<TextView
android:id="#+id/date_booking"
android:text="#string/date_booking"
style="#style/TextAppearance.AppCompat.Medium"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:layout_marginEnd="8dp"
android:lines="1"
android:textFontWeight="900"
android:textSize="#dimen/_15sdp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.888"/>
</androidx.constraintlayout.widget.ConstraintLayout>
</LinearLayout>
</RelativeLayout>
When you are setting the Adapter, stockBookingList is empty.
This means that when RecyclerView decides to render items on the list, it finds the itemCount to be 0.
This instructs the RecylcerView to not render anything on the list, since it won't call onCreateViewHolder or onBindViewHolder – two methods responsible for inflating your list item and setting necessary data.
If you have a static list of items, you need to provide them to the adapter.
If the list is coming from your RestClient, you need update the adapter as and when you receive data from your API.

RecyclerView Margin

i am developing application for home security. One of the feature, that must be implemented is the ability to see connected devices (for sending notifications, blocking access, etc). So far, i've been able to create RecyclerView list of the devices, everything is perfect (for me), except that cards in this list have no spacing between them.
Screenshot of how it looks now
device_data_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:cardview="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="80dp"
android:layout_margin="8dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="80dp">
<ImageView
android:id="#+id/deviceIcon"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:scaleType="centerCrop"
android:layout_marginLeft="8dp" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="80dp"
android:layout_alignBottom="#+id/deviceIcon"
android:layout_toEndOf="#+id/deviceIcon">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Username"
android:id="#+id/deviceUsername"
android:layout_gravity="center_vertical"
android:textColor="#000000"
android:layout_marginLeft="5dp" />
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="50dp"
android:layout_gravity="center_vertical"
android:gravity="center_vertical|center_horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="25dp"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Device Model"
android:gravity="center_vertical|right"
android:textColor="#000000"
android:id="#+id/deviceModel"
android:layout_marginLeft="5dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="25dp"
android:textColor="#000000"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Device Version"
android:gravity="center_vertical|right"
android:id="#+id/deviceVersion"
android:layout_marginLeft="5dp" />
</LinearLayout>
</LinearLayout>
devices_list.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="#dimen/activity_vertical_margin">
<view
android:id="#+id/connectedDevicesList"
class="android.support.v7.widget.RecyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerInParent="true" />
</RelativeLayout>
View Holder Code
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.exampleapp.R;
public class DeviceViewHolder extends RecyclerView.ViewHolder {
protected ImageView deviceIcon;
protected TextView deviceUsername;
protected TextView deviceModel;
protected TextView deviceVersion;
public DeviceViewHolder(View view) {
super(view);
this.deviceIcon = (ImageView) view.findViewById(R.id.deviceIcon);
this.deviceUsername = (TextView) view.findViewById(R.id.deviceUsername);
this.deviceModel = (TextView) view.findViewById(R.id.deviceModel);
this.deviceVersion = (TextView) view.findViewById(R.id.deviceVersion);
}
}
RecyclerView Adapter
import android.content.Context;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.List;
import com.exampleapp.API.AuthorizedDevice;
import com.exampleapp.R;
public class ConnectedDeviceAdapter extends RecyclerView.Adapter<DeviceViewHolder> {
private List<AuthorizedDevice> devices;
private Context mContext;
public ConnectedDeviceAdapter(Context context, List<AuthorizedDevice> devices) {
this.devices = devices;
this.mContext = context;
}
#Override
public DeviceViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.connected_devices_layout, null);
DeviceViewHolder viewHolder = new DeviceViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(DeviceViewHolder deviceViewHolder, int i) {
AuthorizedDevice device = devices.get(i);
if (device.getDeviceId().equals("0")) {
deviceViewHolder.deviceIcon.setBackground(ContextCompat.getDrawable(mContext, R.drawable.android_icon));
} else {
deviceViewHolder.deviceIcon.setBackground(ContextCompat.getDrawable(mContext, R.drawable.apple_icon));
}
deviceViewHolder.deviceUsername.setText(device.getUsername());
deviceViewHolder.deviceModel.setText(device.getDeviceName());
deviceViewHolder.deviceVersion.setText(device.getDeviceVersion());
}
#Override
public int getItemCount() {
return (null != devices ? devices.size() : 0);
}
}
Can anyone please help me solve this problem? Thank you very much in advance!
In your RecyclerView Adapter onCreateViewHolder:
replace:
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.connected_devices_layout, null);
with:
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.connected_devices_layout, viewGroup, false);
Or you can use RecyclerView.addItemDecoration(ItemDecoration decor).

My Android Application Is Giving Fragment Not Attached To Activity Error.

//Here Is My Code
My target is to add a custom listview on fragment and fire it on activity creation
// FragmentSongs.java
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;
public class FragmentSongs extends ListFragment implements OnItemClickListener {
ListView listview;
String[] Songs=getResources().getStringArray(R.string.songs);
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
MyAdapter adapter=new MyAdapter(getActivity(),Songs);
listview.setAdapter(adapter);
listview.setOnItemClickListener(this);
View myview=inflater.inflate(R.layout.fragment_songs, container,false);
return myview;
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Toast.makeText(getActivity(), Songs[position], Toast.LENGTH_SHORT).show();
}
}
// MyAdapter.java
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class MyAdapter extends ArrayAdapter<String>{
Context context;
String[] songs;
LayoutInflater inflater;
public MyAdapter(Context context,String[] songs) {
super(context,R.layout.songlist_row);
this.context=context;
this.songs=songs;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView==null)
{
inflater=(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView=inflater.inflate(R.layout.songlist_row, null);
}
TextView tv1=(TextView) convertView.findViewById(R.id.textView1);
tv1.setText(songs[position]);
return convertView;
}
}
// MainActivity.java
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
public class MainActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
System.out.print("Reached");
FragmentSongs songs=new FragmentSongs();
FragmentManager fm=getSupportFragmentManager();
FragmentTransaction transaction=fm.beginTransaction();
transaction.add(R.id.fragment1,songs);
transaction.commit();
}
}
// activitymain.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="wrap_content"
android:id="#+id/activitylayout"
android:orientation="vertical">
<fragment
android:id="#+id/fragment1"
android:name="android.app.ListFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
//
this is the name of my fragment which i want to attach to activitymain
fragment_songs.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:android1="http://schemas.android.com/apk/res/android"
android:id="#+id/fragment1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:baselineAligned="false" >
<ListView
android1:id="#+id/listView1"
android1:layout_width="match_parent"
android1:layout_height="0dp"
android1:layout_weight="1" >
</ListView>
</LinearLayout>
// songlist_row.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="10dp"
android:background="#1A237E" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:text="Large Text"
android:background="#C5CAE9"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/textView1"
android:background="#C5CAE9"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/textView2"
android:layout_alignBottom="#+id/textView2"
android:layout_alignRight="#+id/textView1"
android:layout_toRightOf="#+id/textView2"
android:background="#C5CAE9"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium" />
</RelativeLayout>
There are two ways of inserting a fragment of an activity and you are using both at the same time.
The first way is:
Declare the fragment inside the activity's layout file.
But in this case the fragment will be fixed on the activity like a view.
The second form is:
Programmatically add the fragment to an existing ViewGroup.
In this case you can add the fragment at any time to the activity, replace it with another fragment, remove the fragment when you want.
You can see what I'm telling you watching this link to the Android developer and looking "Adding a fragment to an activity".
Fragments Android Developers
Note: If you decide to programmatically add the fragment do not have to reference it in the XML Activity. On the other hand these lines would thus:
FragmentSongs songs=new FragmentSongs();
FragmentManager fm=getSupportFragmentManager();
FragmentTransaction transaction=fm.beginTransaction();
transaction.add(R.id.content,songs);
transaction.commit();
R.id.content: It is the id of the container in which you add the fragment programmatically in your case on the activitymain.xml LinearLayout. As you can see you did not like this but you linked the id of the fragment which is a mistake.
Well do not forget that you should not use two ways of adding the fragments so pick one and hope that what prompted you find it useful.

Unable to start activity with the click of an image button

I have made a custom theme for my action bar so that it displays three buttons on the top of the screen. With the click of the leftmost button, I want to start a new activity. However, I am unable to do so. I have used the correct method to start an activity and I am still getting an error. I don't know what the problem is.
The code I have written so far.
MainActivity.java
package com.example.contactmanager1;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ListAdapter;
import android.widget.ListView;
public class MainActivity extends Activity {
private ListView listView;
private ImageButton button1;
private ImageButton button2;
private ImageButton button3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getActionBar().setDisplayShowTitleEnabled(false);
getActionBar().setHomeButtonEnabled(false);
getActionBar().setDisplayShowCustomEnabled(true);
getActionBar().setCustomView(R.layout.button_layout);
getActionBar().setDisplayShowHomeEnabled(false);
listView = (ListView)findViewById(R.id.main_contact_listview);
button1= (ImageButton)findViewById(R.id.button_search);
button2= (ImageButton)findViewById(R.id.button_addcontact);
button3= (ImageButton)findViewById(R.id.button_options);
setUpListView();
}
private void setUpListView(){
List <String> displayList = new ArrayList<String>();
displayList.add("Display Item 1");
displayList.add("Display Item 2");
displayList.add("Display Item 3");
ListAdapter listAdapter = new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_list_item_1,displayList);
listView.setAdapter(listAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
return true;
}
public boolean onOptionsItemSelected(MenuItem item){
//Handle presses on the action bar items
switch(item.getItemId()){
case R.id.action_button_groups:
Intent intent = new Intent(this,Groups.class);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void addContact(View view){
Intent intent = new Intent(this,AddContact.class);
startActivity(intent);
}
public void groupPage(View view){
Intent intent = new Intent(this,Groups.class);
startActivity(intent);
}
}
button_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:gravity="center"
android:background="#android:color/holo_blue_dark"
android:padding="5dp"
android:layout_weight="1">
<ImageButton
android:id="#+id/action_button_groups"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/groups"
android:onClick="groupPage" />
</LinearLayout>
<View
android:layout_width="1dp"
android:layout_height="match_parent"
android:background="#android:color/white"/>
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:gravity="center"
android:background="#android:color/holo_blue_dark"
android:padding="5dp"
android:layout_weight="1">
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/contactlist" />
</LinearLayout>
<View
android:layout_width="1dp"
android:layout_height="match_parent"
android:background="#android:color/white"/>
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:gravity="center"
android:background="#android:color/holo_blue_dark"
android:padding="5dp"
android:layout_weight="1">
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/favourites" />
</LinearLayout>
</LinearLayout>
</FrameLayout>
For the first image button in button_layout.xml I have added a onClick attribute to which points to the method groupPage. I have defined this method in MainActivity.java.
listView with a imagebutton causes problem as it consumes all touches to it.so try replacing the imagebutton with imageView or try this link.try this link

How to use two or multiple xml file in android

i am developing egreeting card application.i have two xml file in first xml file it contain buttons and list view.when i click on button list will display this list occupy the space of activity.So we cant put any widget in xml file.When click on list item i want to shows ImageView at same place of list .For to achieve this i created another xml and put ImageView inside that.now when i click on ListItem it new xml shows but not in same activiy.how could solve this.i attached full source code here. here is my xml files
main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#color/backcolor"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#color/linearback" >
<ImageButton
android:id="#+id/imageButton1"
android:layout_width="40dp"
android:layout_height="30dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:background="#drawable/list_items" />
<ImageButton
android:id="#+id/imageButton2"
android:layout_width="50dp"
android:layout_height="40dp"
android:layout_marginLeft="190dp"
android:layout_marginTop="6dp"
android:background="#drawable/search" />
</LinearLayout>
<!--
<LinearLayout
android:id="#+id/mylayouttwo"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView android:id="#+id/imgview1"
android:layout_width="match_parent"
android:layout_height="300dp"></ImageView>
</LinearLayout>
-->
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
images.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="horizontal"
android:background="#color/backcolor">
<ImageView
android:id="#+id/imageView1"
android:layout_width="match_parent"
android:layout_height="234dp"
android:layout_marginTop="60dp"
android:src="#drawable/ic_launcher" />
</LinearLayout>
package com.triumph.greetings;
import android.R.color;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewSwitcher;
public class Launch extends Activity implements OnClickListener {
boolean isListVisible=true;
ImageButton img1,img2;
ListView lv;
String[] festivales= new String[]{"Christmas","New year","BirthDay","Easter","Wedding","Valentine","Love","Nature"};
ImageView img;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
img1=(ImageButton)findViewById(R.id.imageButton1);
img2=(ImageButton)findViewById(R.id.imageButton2);
img1.setOnClickListener(this);
img2.setOnClickListener(this);
lv=(ListView)findViewById(R.id.listView1);
ArrayAdapter<String> adapter=new ArrayAdapter<String>(Launch.this,android.R.layout.simple_list_item_1,festivales);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> arg0, View v, int postion,
long arg3)
{
// TODO Auto-generated method stub
lv.setVisibility(View.INVISIBLE);
isListVisible=false;
Toast.makeText( Launch.this, ((TextView) v).getText(),Toast.LENGTH_LONG).show();
//state=true;
displayimages();
}
private void displayimages()
{
// TODO Auto-generated method stub
// fetch the images from server and shows in GridView
// call linear layout
setContentView(R.layout.images);
img=(ImageView)findViewById(R.id.imageView1);
img.setBackgroundColor(color.background_light);
}
});
}
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
switch(v.getId())
{
case R.id.imageButton1:
if(isListVisible)
{
lv.setVisibility(View.INVISIBLE);
isListVisible=false;
}
else
{
lv.setVisibility(View.VISIBLE);
isListVisible=true;
}
break;
//Toast.makeText(getBaseContext(), "Hi", Toast.LENGTH_LONG).show();break;
case R.id.imageButton2:
break;
}
}
}

Categories

Resources