I want to display pie-chart in a fragment dialog box..
This is the code:--
MainActivity.java
public class MainActivity extends Activity implements
MyDialogFragment.Communicator {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#SuppressLint("NewApi")
public void showDialog(View view) {
FragmentManager manager = getFragmentManager();
MyDialogFragment1 mydialog = new MyDialogFragment1();
mydialog.show(manager, "mydialog");
}
#Override
public void message(String data) {
Toast.makeText(getApplicationContext(), data + " button clicked",
Toast.LENGTH_SHORT).show();
}
}
and the MyDialogFragment1.java
#SuppressLint({ "NewApi", "InflateParams" })
public class MyDialogFragment1 extends DialogFragment implements OnClickListener {
Button no_button;
Context context;
private static int[] COLORS = new int[] { Color.MAGENTA, Color.CYAN };
private static String[] NAME_LIST = new String[] { "A", "B" };
private CategorySeries mSeries = new CategorySeries("");
private DefaultRenderer mRenderer = new DefaultRenderer();
private GraphicalView mChartView;
private int[] VALUES = { 40, 60 };
Communicator communicator;
#SuppressLint("NewApi")
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (activity instanceof Communicator) {
communicator = (Communicator) getActivity();
} else {
throw new ClassCastException(activity.toString()
+ " must implemenet MyListFragment.communicator");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
setCancelable(false);
getDialog().setTitle("Title");
// View view = inflater.inflate(R.layout.main, null, false);
View view = (LinearLayout) inflater.inflate(R.layout.main,container, false);
mRenderer.setApplyBackgroundColor(true);
mRenderer.setBackgroundColor(Color.argb(100, 50, 50, 50));
mRenderer.setChartTitleTextSize(20);
mRenderer.setLabelsTextSize(15);
mRenderer.setLegendTextSize(15);
mRenderer.setMargins(new int[] { 20, 30, 15, 0 });
mRenderer.setZoomButtonsVisible(true);
mRenderer.setStartAngle(90);
for (int i = 0; i < VALUES.length; i++) {
//mSeries.add(NAME_LIST[i] + " " + VALUES[i], VALUES[i]);
mSeries.add(NAME_LIST[i] + "(" + VALUES[i]+"%)", VALUES[i]);
SimpleSeriesRenderer renderer = new SimpleSeriesRenderer();
renderer.setColor(COLORS[(mSeries.getItemCount() - 1) % COLORS.length]);
mRenderer.addSeriesRenderer(renderer);
}
if (mChartView != null) {
mChartView.repaint();
}
//yes_button = (Button) view.findViewById(R.id.yesbtn);
no_button = (Button) view.findViewById(R.id.nobtn);
// setting onclick listener for buttons
// yes_button.setOnClickListener(this);
no_button.setOnClickListener(this);
return view;
}
#SuppressLint("ShowToast")
#Override
public void onResume() {
super.onResume();
if (mChartView == null) {
LinearLayout layout = (LinearLayout) findViewById(R.id.chart);
mChartView = ChartFactory.getPieChartView(context, mSeries, mRenderer ) ;
mRenderer.setClickEnabled(true);
mRenderer.setSelectableBuffer(10);
mChartView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SeriesSelection seriesSelection = mChartView.getCurrentSeriesAndPoint();
}
});
mChartView.setOnLongClickListener(new View.OnLongClickListener() {
#SuppressLint("ShowToast")
#Override
public boolean onLongClick(View v) {
SeriesSelection seriesSelection = mChartView.getCurrentSeriesAndPoint();
return false;
}
});
layout.addView(mChartView, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
}
else {
mChartView.repaint();
}
}
private LinearLayout findViewById(int chart) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.nobtn :
dismiss();
communicator.message("Dialog No btn clicked");
break;
}
}
public interface Communicator {
public void message(String data);
}
}
and the xml files are:--
activity_main.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"
android:padding="20dp" >
<Button
android:id="#+id/button1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="showDialog"
android:text="Show Dialog" />
</LinearLayout>
and main.xml is :--
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/chart"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="horizontal" >
</LinearLayout>
<Button
android:id="#+id/nobtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/yesbtn"
android:layout_alignBottom="#+id/yesbtn"
android:layout_alignRight="#+id/textView1"
android:layout_marginRight="38dp"
android:text="No" />
</LinearLayout>
Now, When I run this program it shows the button,when I click the button it stops...
and showing the following error:--
FATAL EXCEPTION: main
Process: com.emple.dialog_android_example, PID: 21181
java.lang.ClassCastException: com.emple.dialog_android_example.MainActivity#41ef95b0 must implemenet MyListFragment.communicator
at com.emple.dialog_android_example.MyDialogFragment1.onAttach(MyDialogFragment1.java:64)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:849)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1062)
at android.app.BackStackRecord.run(BackStackRecord.java:698)
at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1447)
at android.app.FragmentManagerImpl$1.run(FragmentManager.java:443)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5324)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:824)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)
at dalvik.system.NativeStart.main(Native Method)
where is the problem????
I think your activity is not a instance of Communicator
Check here :
#SuppressLint("NewApi")
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (activity instanceof Communicator) {
communicator = (Communicator) getActivity();
} else {
throw new ClassCastException(activity.toString()
+ " must implemenet MyListFragment.communicator");
}
}
Related
I have a fragment with this view:
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"
android:tag="general"
android:id="#+id/root"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#343535"
android:orientation="vertical"
tools:context=".fragments.GeneralFragment">
<Button
android:id="#+id/hello"
android:layout_width="match_parent"
android:layout_height="60dp"
android:gravity="center_vertical"
android:onClick="onClick"
android:text="#string/hello" />
<Button
android:id="#+id/observed"
android:layout_width="match_parent"
android:layout_height="60dp"
android:gravity="center_vertical"
android:onClick="onClick"
android:text="#string/observed" />
<Button
android:id="#+id/thanks"
android:layout_width="match_parent"
android:layout_height="60dp"
android:gravity="center_vertical"
android:onClick="onClick"
android:text="#string/thanks" />
</LinearLayout>
There are 3 buttons. Whenever you click on one of them, its text will be displayed.
Now I would like to add another button but dynamically. It should be added before #+id/hello.
I have tried it with
LinearLayout root = (LinearLayout) view.findViewById(R.id.root);
root.addView();
but it looks completely wrong since some parameters are missing.
For instance, the new button should be like:
XML:
<Button
android:layout_width="match_parent"
android:layout_height="60dp"
android:gravity="center_vertical"
android:onClick="onClick"
android:text="I am a dynamic text" />
This button should be saved permanently in the app. How can I do this?
Update
I am using a dialog, so this is the class:
#SuppressLint("ValidFragment")
public class Dialog extends DialogFragment {
private final int _layout;
private TextInputEditText _customTextField;
#SuppressLint("ValidFragment")
public Dialog(int layout) {
_layout = layout;
}
public interface ICustomTts {
void customTts(String input, Activity activity);
}
public ICustomTts iCustomTts;
public interface ITarget {
void getTarget(String input);
}
public ITarget iTarget;
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate(_layout, container, false);
// Display fragment_custom
if (_layout == R.layout.fragment_custom) {
_customTextField = view.findViewById(R.id.customTextField);
Button _customBtn = view.findViewById(R.id.customCta);
_customBtn.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onClick(View view) {
Log.d(TAG, "onClick: Clicked on CTA of custom");
String input = _customTextField.getText().toString();
if (!input.equals("")) {
iCustomTts.customTts(input, getActivity());
_dismiss();
}
}
});
MaterialCheckBox customeSave = view.findViewById(R.id.customSave);
customeSave.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onClick(View v) {
Log.d(TAG, "customeSave was clicked!");
LinearLayout root = view.findViewById(R.id.root);
Button button = new Button(getContext());
float heightInPixel = 60 * getResources().getDisplayMetrics().density;
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, (int) heightInPixel);
params.gravity = Gravity.CENTER;
button.setText("I am a dynamic text");
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Do the stuff on the click
}
});
root.addView(button, 0);
}
});
}
// Display fragment_target
if (_layout == R.layout.fragment_target) {
_customTextField = view.findViewById(R.id.targetTextField);
Button _customBtn = view.findViewById(R.id.targetCta);
_customBtn.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onClick(View view) {
Log.d(TAG, "onClick: Clicked on CTA of target");
String input = _customTextField.getText().toString();
if (!input.equals("")) {
iTarget.getTarget(input);
_dismiss();
}
}
});
}
return view;
}
/**
* Dismissing the dialog
*/
private void _dismiss() {
this.dismiss();
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
try {
if (_layout == R.layout.fragment_custom) {
iCustomTts = (ICustomTts) getActivity();
}
else if (_layout == R.layout.fragment_target) {
iTarget = (ITarget) getActivity();
}
}
catch (ClassCastException e) {
Log.e(TAG, "onAttach: ClassCastException: " + e.getMessage());
}
}
}
You need to use the two-argument version of addView() to determine the order (index) of the button inside the LinearLayout:
LinearLayout root = view.findViewById(R.id.root);
Button button = new Button(requireContext());
float heightInPixel = 60 * getResources().getDisplayMetrics().density;
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, (int) heightInPixel);
params.gravity = Gravity.CENTER;
button.setText("I am a dynamic text");
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Do the stuff on the click
}
});
root.addView(button, 0);
I'm trying to implement the "swipe to refresh" in my fragment. I did it by inserting a timer in my main activity, by using the Timer class, which refresh, but I would like to improve it by implementing a function directly inside the fragment itself. This is the code:
public class HomeFragment extends Fragment {
private RecyclerView recyclerView;
public HomeFragment() {
}
public static HomeFragment newInstance(String param1, String param2) {
HomeFragment fragment = new HomeFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.main_fragment, container, false);
recyclerView = view.findViewById(R.id.rc_view);
loadMovie();
return view;
}
private void loadMovie() {
ApiService apiService = ApiBuilder.getClient(getContext()).create(ApiService.class);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext(),LinearLayoutManager.HORIZONTAL, false));
Call<MovieResponse> call = apiService.getDiscover(BuildConfig.API_KEY,Values.LANGUAGE,Values.SORT_BY[0], Values.ADULT, Values.GENRE[1], Values.PAGE[0]);
call.enqueue(new Callback<MovieResponse>() {
#Override
public void onResponse(Call<MovieResponse>call, Response<MovieResponse> response) {
final List<MovieModel> movies = response.body().getResults();
recyclerView.setAdapter(new MoviesAdapter(movies, R.layout.content_main, getContext()));
recyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
GestureDetector gestureDetector = new GestureDetector(getContext(), new GestureDetector.SimpleOnGestureListener() {
public boolean onSingleTapUp(MotionEvent e){
return true;
}
});
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && gestureDetector.onTouchEvent(e)){
int position = rv.getChildAdapterPosition(child);
Intent i = new Intent(getContext(), DetailActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtra(DetailActivity.EXTRA_TITLE, movies.get(position).getTitle());
i.putExtra(DetailActivity.EXTRA_OVERVIEW, movies.get(position).getOverview());
i.putExtra(DetailActivity.EXTRA_TIME, movies.get(position).getReleaseDate());
i.putExtra(DetailActivity.EXTRA_POSTER, movies.get(position).getPosterPath());
i.putExtra(DetailActivity.EXTRA_LANGUAGE, movies.get(position).getOriginalLanguage());
try{
List<Integer> genr = movies.get(position).getGenreIds();
i.putExtra(DetailActivity.EXTRA_GENRES, genr.toString());
} catch (Exception ex) {
ex.printStackTrace();
}
getContext().startActivity(i);
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
});
if (movies != null ){
MovieModel firstMovie = movies.get(0);
if(firstMovie != null) {
Log.i("TAG", firstMovie.getTitle());
}
}
}
#Override
public void onFailure(Call<MovieResponse>call, Throwable t) {
}
});
}
}
This is the Timer I implemented in the main activity, which I want to remove:
TimerTask timertask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
startService(new Intent(MainActivity.this, TimerService.class));
}
});
}
};
Timer timer = new Timer();
timer.schedule(timertask, 0, 10*SECONDS);
EDIT:
I updated my code by implementing the SwipeRefreshLayout inside the onCreate method but it still doesn't works:
mPullToRefresh = view.findViewById(R.id.swipe_list);
final Handler handler = new Handler();
mPullToRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
handler.postDelayed(new Runnable() {
#Override
public void run() {
loadMovie(); //load your moview from here
mPullToRefresh.setRefreshing(false);
}
}, 1000);
}
});
This is my fragment layout updated:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Movies"
android:layout_marginLeft="#dimen/_10sdp"
android:layout_marginRight="#dimen/_10sdp"
android:textSize="#dimen/_20ssp"
android:textStyle="bold"
android:textColor="#ffffff"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/_5sdp"
android:text="Action"
android:layout_marginLeft="#dimen/_10sdp"
android:layout_marginRight="#dimen/_10sdp"
android:textSize="#dimen/_12ssp"
android:textColor="#color/colorAccent"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="#dimen/_150sdp"
android:layout_marginTop="#dimen/_10sdp"
android:orientation="vertical">
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:id="#+id/rc_view"/>
</LinearLayout>
<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
android:id="#+id/swipe_list"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycler_view_list"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
</LinearLayout>
There is a Layout to implement the functionality.
Put this in your fragment xml file:-
<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
android:id="#+id/swipe_list"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycler_view_list"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
Now in your Fragment:-
1) do the
SwipeRefreshLayout mPullToRefresh = view.findViewById(R.id.swipe_list)
2) then,
mPullToRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
loadMovie(); //load your moview from here
mPullToRefresh.setRefreshing(false);
}
}, 1000);
}
});
Please Up-Vote If Found Useful.
I have ListView with a custom list layout. I am using an ArrayList and ArrayAdapter for this. I am having a difficult time removing selected items from the arraylist. I am not sure want I am doing wrong. Here's an example of a arraylist that I have:
Item A
Item B
Item C
Item D
Let's say that I selected Item C next on button clicked labeled "Remove" I want Item C removed from the list. How do I accomplish this? Currently my code only removes the item on index 0. I want selected item index to be removed.
Here's my codes...
Java Class:
public class MainActivity extends AppCompatActivity {
ListView lstVw;
Button addBtn, removeBtn, clearListBtn;
ArrayList<String> arrayList;
ArrayAdapter<String> adapter;
int getPosition = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lstVw = findViewById(R.id.lstView);
addBtn = findViewById(R.id.add_item_btn);
removeBtn = findViewById(R.id.remove_item_btn);
clearListBtn = findViewById(R.id.clear_list_btn);
arrayList = new ArrayList<>();
adapter = new ArrayAdapter<>(getApplicationContext(), R.layout.item_list, R.id.item_tv, arrayList);
lstVw.setAdapter(adapter);
lstVw.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String getItem = adapter.getItem(position);
getPosition = Integer.parseInt(getItem);
}
});
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final AlertDialog.Builder adb = new AlertDialog.Builder(MainActivity.this);
adb.setTitle("Enter Item Name");
final EditText itemTxt = new EditText(MainActivity.this);
itemTxt.setText(getString(R.string.default_item_name_value));
itemTxt.setInputType(InputType.TYPE_CLASS_TEXT);
adb.setView(itemTxt);
adb.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String getItem = itemTxt.getText().toString();
Set<String> s = new LinkedHashSet<>(arrayList);
if (s.contains(getItem)) {
arrayList.clear();
arrayList.addAll(s);
Toast.makeText(getApplicationContext(), getItem + " already exists in the list!", Toast.LENGTH_LONG).show();
} else {
arrayList.add(getItem);
adapter.notifyDataSetChanged();
}
}
});
adb.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
adb.create();
adb.show();
}
});
clearListBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!arrayList.isEmpty()) {
arrayList.clear();
adapter.notifyDataSetChanged();
}
}
});
removeBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String getItem = arrayList.get(getPosition);
arrayList.remove(getItem);
adapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), getItem + " is removed!", Toast.LENGTH_LONG).show();
}
});
}
}
Main 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:id="#+id/rl"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<ScrollView
android:layout_width="match_parent"
android:layout_height="650dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="650dp">
<ListView
android:id="#+id/lstView"
android:layout_width="match_parent"
android:layout_height="650dp"
tools:ignore="NestedScrolling" />
</RelativeLayout>
</ScrollView>
<include layout="#layout/action_buttons"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"/>
Action Buttons XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:layout_gravity="center|top">
<Button
android:id="#+id/add_item_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:textAllCaps="false"
android:text="#string/add_item_text"
android:textSize="14sp"
android:textStyle="bold"
android:textColor="#android:color/black"/>
<Button
android:id="#+id/remove_item_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_toEndOf="#id/add_item_btn"
android:textAllCaps="false"
android:text="Remove Item"
android:textColor="#android:color/black"
android:textSize="14sp"
android:textStyle="bold"/>
<Button
android:id="#+id/clear_list_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_toEndOf="#id/remove_item_btn"
android:textAllCaps="false"
android:text="#string/clear_list_text"
android:textSize="14sp"
android:textStyle="bold"
android:textColor="#android:color/black"/>
My Custom List Layout XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/item_tv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textStyle="bold"
android:textSize="20sp"
android:textColor="#android:color/black"/>
</ScrollView>
I appreciate the help! Thanks!
removeBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String getItem = arrayList.get(getPosition);
arrayList.remove(getItem);
adapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), getItem + " is removed!", Toast.LENGTH_LONG).show();
}
});
From where are you getting this getPosition?
It looks to me like your int getPosition = 0; variable is not getting updated with your new position. On your click listener you are trying to parse the value of your selected item to an Integer, maybe you could try simply updating with the current position instead?
lstVw.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
getPosition = position;
}
});
Edit:
You could go with something like this:
Create an interface that your activity will implement and will be used by your adapter to notify a position change:
public interface PositionChangeListener {
void onPositionChanged(int newPosition);
}
Create a custom adapter:
public class CustomAdapterView extends BaseAdapter {
private Context context;
private PositionChangeListener listener;
private ArrayList<String> items;
public CustomAdapterView(Context context, ArrayList<String> items, PositionChangeListener listener) {
this.context = context;
this.items = items;
this.listener = listener;
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int position) {
return items.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder = null;
if (convertView == null) {
convertView = LayoutInflater.from(context).inflate( R.layout.item_list, null);
viewHolder = new ViewHolder();
viewHolder.txt = convertView.findViewById(R.id.item_tv);
viewHolder.txt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
listener.onPositionChanged(position);
}
});
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.txt.setText(items.get(position));
return convertView;
}
private class ViewHolder {
TextView txt;
}
}
And now in your activity:
public class MainActivity extends AppCompatActivity implements PositionChangeListener{
ListView lstVw;
Button addBtn, removeBtn, clearListBtn;
ArrayList<String> arrayList;
BaseAdapter adapter;
int getPosition = 0;
#Override
public void onPositionChanged(int newPosition) {
getPosition = newPosition;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lstVw = findViewById(R.id.lstView);
addBtn = findViewById(R.id.add_item_btn);
removeBtn = findViewById(R.id.remove_item_btn);
clearListBtn = findViewById(R.id.clear_list_btn);
arrayList = new ArrayList<>();
adapter = new CustomAdapterView(this, arrayList, this);
lstVw.setAdapter(adapter);
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final AlertDialog.Builder adb = new AlertDialog.Builder(MainActivity.this);
adb.setTitle("Enter Item Name");
final EditText itemTxt = new EditText(MainActivity.this);
itemTxt.setText("default item name");
itemTxt.setInputType(InputType.TYPE_CLASS_TEXT);
adb.setView(itemTxt);
adb.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String getItem = itemTxt.getText().toString();
Set<String> s = new LinkedHashSet<>(arrayList);
if (s.contains(getItem)) {
arrayList.clear();
arrayList.addAll(s);
Toast.makeText(getApplicationContext(), getItem + " already exists in the list!", Toast.LENGTH_LONG).show();
} else {
arrayList.add(getItem);
adapter.notifyDataSetChanged();
}
}
});
adb.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
adb.create();
adb.show();
}
});
clearListBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!arrayList.isEmpty()) {
arrayList.clear();
adapter.notifyDataSetChanged();
}
}
});
removeBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String getItem = arrayList.get(getPosition);
arrayList.remove(getItem);
adapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), getItem + " is removed!", Toast.LENGTH_LONG).show();
}
});
}
}
I am new to android development and I am confused about how to add admob banner to a fragment activity(I think its calling fragment). I am modifying a source code.
I have a layout file called fragment_ftp.xml and its as below
<?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"
xmlns:ads="http://schemas.android.com/apk/res-auto">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text=""
android:id="#+id/statusText"
android:layout_above="#+id/startStopButton"
android:layout_centerHorizontal="true"
android:layout_marginBottom="99dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text=""
android:id="#+id/ftpAddressText"
android:layout_below="#+id/startStopButton"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/start_ftp"
android:id="#+id/startStopButton"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#color/primary_red"
android:text=""
android:id="#+id/warningText"
android:layout_above="#+id/startStopButton"
android:layout_centerHorizontal="true" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/ftp_image"
android:layout_above="#+id/warningText"
android:layout_centerHorizontal="true" />
<RelativeLayout
android:id="#+id/relativeLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true">
<com.google.android.gms.ads.AdView
android:id="#+id/adView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
ads:adSize="SMART_BANNER"
ads:adUnitId="#string/banner_home_footer" />
</RelativeLayout>
</RelativeLayout>
I had added the admob banner and in the preview, I can see that. Please check the below screenshot.
But the issues is that, Where should I write the java code for this admob banner. I don't have a corresponding activity for this fragment_ftp.xml.
Searching for fragment_ftp, I could see only a java file as follows.
FTPServerFragment.java
package com.filename.fragments;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
public class FTPServerFragment extends Fragment {
TextView statusText,warningText,ftpAddrText;
Button ftpBtn;
Futils utils = new Futils();
private MainActivity mainActivity;
private View rootView;
private BroadcastReceiver mWifiReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager conMan = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = conMan.getActiveNetworkInfo();
if (netInfo != null && netInfo.getType() == ConnectivityManager.TYPE_WIFI){
warningText.setText("");
}
else{
stopServer();
statusText.setText(utils.getString(getContext(),R.string.ftp_status_not_running));
warningText.setText(utils.getString(getContext(),R.string.ftp_no_wifi));
ftpAddrText.setText("");
ftpBtn.setText(utils.getString(getContext(),R.string.start_ftp));
}
}
};
private BroadcastReceiver ftpReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(action == FTPService.ACTION_STARTED) {
statusText.setText(utils.getString(getContext(), R.string.ftp_status_running));
warningText.setText("");
ftpAddrText.setText(getFTPAddressString());
ftpBtn.setText(utils.getString(getContext(),R.string.stop_ftp));
}
else if(action == FTPService.ACTION_FAILEDTOSTART){
statusText.setText(utils.getString(getContext(),R.string.ftp_status_not_running));
warningText.setText("Oops! Something went wrong");
ftpAddrText.setText("");
ftpBtn.setText(utils.getString(getContext(),R.string.start_ftp));
}
else if(action == FTPService.ACTION_STOPPED){
statusText.setText(utils.getString(getContext(),R.string.ftp_status_not_running));
ftpAddrText.setText("");
ftpBtn.setText(utils.getString(getContext(),R.string.start_ftp));
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(false);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
rootView = inflater.inflate(R.layout.fragment_ftp,container,false);
// return inflater.inflate(R.layout.article_view, container, false);
statusText =(TextView) rootView.findViewById(R.id.statusText);
warningText = (TextView) rootView.findViewById(R.id.warningText);
ftpAddrText = (TextView) rootView.findViewById(R.id.ftpAddressText);
ftpBtn = (Button) rootView.findViewById(R.id.startStopButton);
SharedPreferences Sp = PreferenceManager.getDefaultSharedPreferences(getContext());
int th = Integer.parseInt(Sp.getString("theme", "0"));
// checking if theme should be set light/dark or automatic
int theme1 = th == 2 ? PreferenceUtils.hourOfDay() : th;
ImageView ftpImage = (ImageView)rootView.findViewById(R.id.ftp_image);
//light theme
if(theme1 == 0){
ftpImage.setImageResource(R.drawable.ic_ftp_light);
}else{
//dark
ftpImage.setImageResource(R.drawable.ic_ftp_dark);
}
ftpBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
if(!FTPService.isRunning()){
if(FTPService.isConnectedToWifi(getContext()))
startServer();
else
warningText.setText(utils.getString(getContext(),R.string.ftp_no_wifi));
}
else{
stopServer();
}
}
});
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setRetainInstance(true);
mainActivity=(MainActivity)getActivity();
mainActivity.setActionBarTitle(utils.getString(getActivity(), R.string.ftp));
mainActivity.floatingActionButton.hideMenuButton(true);
mainActivity.buttonBarFrame.setVisibility(View.GONE);
mainActivity.supportInvalidateOptionsMenu();
}
#Override
public void onDestroy(){
super.onDestroy();
}
private void startServer() {
getContext().sendBroadcast(new Intent(FTPService.ACTION_START_FTPSERVER));
}
private void stopServer() {
getContext().sendBroadcast(new Intent(FTPService.ACTION_STOP_FTPSERVER));
}
#Override
public void onResume(){
super.onResume();
updateStatus();
IntentFilter wifiFilter = new IntentFilter();
wifiFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
getContext().registerReceiver(mWifiReceiver,wifiFilter);
IntentFilter ftpFilter = new IntentFilter();
ftpFilter.addAction(FTPService.ACTION_STARTED);
ftpFilter.addAction(FTPService.ACTION_STOPPED);
ftpFilter.addAction(FTPService.ACTION_FAILEDTOSTART);
getContext().registerReceiver(ftpReceiver,ftpFilter);
}
#Override
public void onPause(){
super.onPause();
getContext().unregisterReceiver(mWifiReceiver);
getContext().unregisterReceiver(ftpReceiver);
}
private void updateStatus(){
if(FTPService.isRunning()){
statusText.setText(utils.getString(getContext(),R.string.ftp_status_running));
ftpBtn.setText(utils.getString(getContext(),R.string.stop_ftp));
ftpAddrText.setText(getFTPAddressString());
}
else{
statusText.setText(utils.getString(getContext(),R.string.ftp_status_not_running));
ftpBtn.setText(utils.getString(getContext(),R.string.start_ftp));
}
}
private String getFTPAddressString(){
return "ftp://"+FTPService.getLocalInetAddress(getContext()).getHostAddress()+":"+FTPService.getPort();
}
}
I this the java page where I shall write the admob call?
try and use this code solve the issue
http://www.androidhive.info/2016/02/android-how-to-integrate-google-admob-in-your-app/
your code java has to be added inside onCreateView function in FTPServerFragement like this :
public class FTPServerFragment extends Fragment {
TextView statusText,warningText,ftpAddrText;
Button ftpBtn;
Futils utils = new Futils();
private MainActivity mainActivity;
private View rootView;
private BroadcastReceiver mWifiReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager conMan = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = conMan.getActiveNetworkInfo();
if (netInfo != null && netInfo.getType() == ConnectivityManager.TYPE_WIFI){
warningText.setText("");
}
else{
stopServer();
statusText.setText(utils.getString(getContext(),R.string.ftp_status_not_running));
warningText.setText(utils.getString(getContext(),R.string.ftp_no_wifi));
ftpAddrText.setText("");
ftpBtn.setText(utils.getString(getContext(),R.string.start_ftp));
}
}
};
private BroadcastReceiver ftpReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(action == FTPService.ACTION_STARTED) {
statusText.setText(utils.getString(getContext(), R.string.ftp_status_running));
warningText.setText("");
ftpAddrText.setText(getFTPAddressString());
ftpBtn.setText(utils.getString(getContext(),R.string.stop_ftp));
}
else if(action == FTPService.ACTION_FAILEDTOSTART){
statusText.setText(utils.getString(getContext(),R.string.ftp_status_not_running));
warningText.setText("Oops! Something went wrong");
ftpAddrText.setText("");
ftpBtn.setText(utils.getString(getContext(),R.string.start_ftp));
}
else if(action == FTPService.ACTION_STOPPED){
statusText.setText(utils.getString(getContext(),R.string.ftp_status_not_running));
ftpAddrText.setText("");
ftpBtn.setText(utils.getString(getContext(),R.string.start_ftp));
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(false);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
rootView = inflater.inflate(R.layout.fragment_ftp,container,false);
// return inflater.inflate(R.layout.article_view, container, false);
statusText =(TextView) rootView.findViewById(R.id.statusText);
warningText = (TextView) rootView.findViewById(R.id.warningText);
ftpAddrText = (TextView) rootView.findViewById(R.id.ftpAddressText);
ftpBtn = (Button) rootView.findViewById(R.id.startStopButton);
//your ads
MobileAds.initialize(this, new OnInitializationCompleteListener() {
#Override
public void onInitializationComplete(InitializationStatus initializationStatus) {
}
});
mAdView = rootView.findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
SharedPreferences Sp = PreferenceManager.getDefaultSharedPreferences(getContext());
int th = Integer.parseInt(Sp.getString("theme", "0"));
// checking if theme should be set light/dark or automatic
int theme1 = th == 2 ? PreferenceUtils.hourOfDay() : th;
ImageView ftpImage = (ImageView)rootView.findViewById(R.id.ftp_image);
//light theme
if(theme1 == 0){
ftpImage.setImageResource(R.drawable.ic_ftp_light);
}else{
//dark
ftpImage.setImageResource(R.drawable.ic_ftp_dark);
}
ftpBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
if(!FTPService.isRunning()){
if(FTPService.isConnectedToWifi(getContext()))
startServer();
else
warningText.setText(utils.getString(getContext(),R.string.ftp_no_wifi));
}
else{
stopServer();
}
}
});
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setRetainInstance(true);
mainActivity=(MainActivity)getActivity();
mainActivity.setActionBarTitle(utils.getString(getActivity(), R.string.ftp));
mainActivity.floatingActionButton.hideMenuButton(true);
mainActivity.buttonBarFrame.setVisibility(View.GONE);
mainActivity.supportInvalidateOptionsMenu();
}
#Override
public void onDestroy(){
super.onDestroy();
}
private void startServer() {
getContext().sendBroadcast(new Intent(FTPService.ACTION_START_FTPSERVER));
}
private void stopServer() {
getContext().sendBroadcast(new Intent(FTPService.ACTION_STOP_FTPSERVER));
}
#Override
public void onResume(){
super.onResume();
updateStatus();
IntentFilter wifiFilter = new IntentFilter();
wifiFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
getContext().registerReceiver(mWifiReceiver,wifiFilter);
IntentFilter ftpFilter = new IntentFilter();
ftpFilter.addAction(FTPService.ACTION_STARTED);
ftpFilter.addAction(FTPService.ACTION_STOPPED);
ftpFilter.addAction(FTPService.ACTION_FAILEDTOSTART);
getContext().registerReceiver(ftpReceiver,ftpFilter);
}
#Override
public void onPause(){
super.onPause();
getContext().unregisterReceiver(mWifiReceiver);
getContext().unregisterReceiver(ftpReceiver);
}
private void updateStatus(){
if(FTPService.isRunning()){
statusText.setText(utils.getString(getContext(),R.string.ftp_status_running));
ftpBtn.setText(utils.getString(getContext(),R.string.stop_ftp));
ftpAddrText.setText(getFTPAddressString());
}
else{
statusText.setText(utils.getString(getContext(),R.string.ftp_status_not_running));
ftpBtn.setText(utils.getString(getContext(),R.string.start_ftp));
}
}
private String getFTPAddressString(){
return "ftp://"+FTPService.getLocalInetAddress(getContext()).getHostAddress()+":"+FTPService.getPort();
}
}
Here's my card view activity where three dots are there as in toolbar and I want to overflow it with menu but getting this error:
java.lang.IllegalStateException: Could not find method showPopup(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatImageButton with id 'img_menu'
Here's XML :
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.CardView
android:id="#+id/card_view"
android:layout_gravity="center"
android:layout_width="fill_parent"
android:layout_height="80dp"
android:layout_margin="5dp"
card_view:cardCornerRadius="2dp"
card_view:contentPadding="10dp"
android:foreground="?android:attr/selectableItemBackground">
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
android:layout_alignParentTop="true"/>
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_below="#+id/textView"/>
<ImageButton
android:id="#+id/img_menu"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/ic_action_navigation_more_vert"
android:layout_alignParentRight="true"
android:layout_marginTop="12dp"
android:onClick="showPopup"/>
</RelativeLayout>
</android.support.v7.widget.CardView>
Here's activity :
public class CardViewActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private static String LOG_TAG = "CardViewActivity";
ImageButton overflowMenu;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_card_view);
overflowMenu = (ImageButton) findViewById(R.id.img_menu);
mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new MyRecyclerViewAdapter(getDataSet());
mRecyclerView.setAdapter(mAdapter);
if (getSupportActionBar() != null) {
getSupportActionBar().setHomeAsUpIndicator(R.drawable.abc_ic_ab_back_mtrl_am_alpha);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void showPopup(View v) {
PopupMenu popup = new PopupMenu(this, v);
MenuInflater inflater = popup.getMenuInflater();
inflater.inflate(R.menu.card_overflow_menu, popup.getMenu());
popup.show();
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.one:
//Or Some other code you want to put here.. This is just an example.
Toast.makeText(getApplicationContext(), " Clicked 1 " + " : " , Toast.LENGTH_LONG).show();
break;
case R.id.two:
Toast.makeText(getApplicationContext(), "Clicked 2 " + " : " , Toast.LENGTH_LONG).show();
break;
default:
break;
}
return true;
}
});
}
/* public void showPopup(View v) {
PopupMenu popup = new PopupMenu(CardViewActivity.this, v);
MenuInflater inflater = popup.getMenuInflater();
inflater.inflate(R.menu.card_overflow_menu,popup.getMenu());
popup.setOnMenuItemClickListener((PopupMenu.OnMenuItemClickListener) {
public boolean onMenuClick (MenuItem item){
}
popup.show();
}}*/
/*public void showMenu(View v) {
PopupMenu popup = new PopupMenu(this, v);
// This activity implements OnMenuItemClickListener
popup.setOnMenuItemClickListener((PopupMenu.OnMenuItemClickListener)
this);
popup.inflate(R.menu.card_overflow_menu);
popup.show();
}*/
#Override
protected void onResume() {
super.onResume();
((MyRecyclerViewAdapter) mAdapter).setOnItemClickListener(new MyRecyclerViewAdapter
.MyClickListener() {
#Override
public void onItemClick(int position, View v) {
Log.i(LOG_TAG, " Clicked on Item " + position);
}
});
}
private ArrayList<DataObject> getDataSet() {
ArrayList results = new ArrayList<DataObject>();
for (int index = 0; index < 20; index++) {
DataObject obj = new DataObject("Test " + index,
"Doc number " + index);
results.add(index, obj);
}
return results;
}
}
LogCat :
java.lang.IllegalStateException: Could not find method showPopup(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatImageButton with id 'img_menu'
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.resolveMethod(AppCompatViewInflater.java:325)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:284)
at android.view.View.performClick(View.java:4802)
at android.view.View$PerformClick.run(View.java:20101)
at android.os.Handler.handleCallback(Handler.java:810)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:189)
at android.app.ActivityThread.main(ActivityThread.java:5532)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:950)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:745)
You are defining onClick event on ImageButton, plus you are setting onClickListener on it too.
Use either
public void showPopup(View v)
code or
overflowMenu.setOnClickListener(new View.OnClickListener()
I suggest you to comment out your overFlowMenu clickListener code.