Changing Gridview Size from Preferences when Implementing Fragments - android

I had a gridview activity where I was populating the gridview with a custom object (a picture with some custom methods and an onclick listener). I could change the gridview size from the preferences menu. Everything worked beautifully.
I have since added some complexity to the code. Instead of using the normal Activity class, I am now using the FragmentActivity class, a fragmentPageAdapter, and a fragment to which my gridview is bound. This is because eventually I want the app to allow the user "swipe" from fragment to fragment.
Since using the fragment in this way, I am noticing a repeatable bug whenever I try to resize the gridview from the preferences menu: some of the objects get resized properly, other elements do not resize. Instead, they keep the same size that they had prior to changing the preference. Here is a screenshot:
This only happens when I try resizing from the preferences menu. Other calls to my resize method, such as on a configuration change, resize all of the gridview elements correctly.
I would appreciate any suggestions!
Here is my Code:
MAIN ACTIVITY:
package com.KhalidSorensen.animalsounds;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.content.res.Configuration;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.GridView;
public class MainActivity extends FragmentActivity implements OnSharedPreferenceChangeListener{
private MyFragment m_myFragment = new MyFragment();
private ViewPager m_viewPager;
private static SharedPreferences m_prefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
m_prefs = PreferenceManager.getDefaultSharedPreferences(this);
m_prefs.registerOnSharedPreferenceChangeListener(this);
setContentView(R.layout.activity_main);
m_viewPager = (ViewPager) findViewById(R.id.pager);
m_viewPager.setAdapter(new MyAdapter(getSupportFragmentManager(), m_myFragment));
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
Log.i("Khalid","MainActivity: onSharedPreferenceChanged");
if (key.equals("key_prefs_enable_lscape")){
//do nothing for now
}else if (key.equals("key_prefs_picture_size")){
SetColumnWidth(m_myFragment.getM_gridView());
}
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
Log.i("Khalid","FragAnimalSounds: onConfigurationChanged");
SetColumnWidth(m_myFragment.getM_gridView());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
Log.i("Khalid","MainActivity: onCreateOptionsMenu");
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.options_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.lbl_opt_menu_settings:
Intent i = new Intent("android.intent.action.PREFERENCES");
startActivity(i);
break;
case R.id.lbl_opt_menu_quit:
finish();
break;
default:
finish();
break;
}
return true;
}
public static void SetColumnWidth(GridView GV) {
Log.i("Khalid","MainActivity: SetColumnWidth");
int NumColumns, DesiredColumnWidth;
//Get the desired number of columns from the key prefs
NumColumns = Integer.parseInt(m_prefs.getString("key_prefs_picture_size","2"));
//Determine the desired column width
if (NumColumns == 1){
DesiredColumnWidth = 200;
}else if (NumColumns == 2){
DesiredColumnWidth = 100;
}else{
DesiredColumnWidth = 50;
}
//Set the desired column width
GV.setColumnWidth(DesiredColumnWidth);
}
}
class MyAdapter extends FragmentPagerAdapter{
Fragment m_frag_A = null;
public MyAdapter(FragmentManager fm, Fragment A) {
super(fm);
m_frag_A = A;
}
#Override
public Fragment getItem(int i) {
return m_frag_A; //only 1 item for now
}
#Override
public int getCount() {
return 1;
}
#Override
public CharSequence getPageTitle(int i) {
return "Title Frag A"; //only 1 item for now
}
}
MY FRAGMENT (THERE IS ONLY ONE FOR NOW):
package com.KhalidSorensen.animalsounds;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
public class MyFragment extends Fragment {
private GridView m_gridView;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
Log.i("Khalid","FragAnimalSounds: onCreateView");
View view = inflater.inflate(R.layout.activity_animal_sounds, container, false);
m_gridView = (GridView) view.findViewById(R.id.lbl_gridView);
m_gridView.setAdapter(new VivzAdapter(view.getContext()));
MainActivity.SetColumnWidth(m_gridView);
return view;
}
public GridView getM_gridView() {
return m_gridView;
}
}
MY GRIDVIEW ADAPTER:
package com.KhalidSorensen.animalsounds;
import java.util.ArrayList;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
public class VivzAdapter extends BaseAdapter {
private Context m_context;
private ArrayList<AnimalKind> m_list = new ArrayList<AnimalKind>();
VivzAdapter(Context ctx) {
m_context = ctx;
int[] animalphotos = { R.drawable.cat_1, R.drawable.cow_1,
R.drawable.dog_1, R.drawable.donkey_1, R.drawable.duck_1,
R.drawable.peacock_1, R.drawable.rooster_1, R.drawable.seal_1 };
for (int i = 0; i <= 7; i++) {
AnimalKind animalKind = new AnimalKind(m_context, animalphotos[i]);
m_list.add(animalKind);
}
}
#Override
public int getCount() {
return m_list.size();
}
#Override
public AnimalKind getItem(int position) {
return m_list.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int i, View v, ViewGroup vg) {
return m_list.get(i);
}
}
MY CUSTOM OBJECT CLASS. THESE OBJECTS ARE POPULATING THE GRIDVIEW:
package com.KhalidSorensen.animalsounds;
import android.content.Context;
import android.graphics.Color;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
public class AnimalKind extends ImageView implements OnClickListener{
private int m_imageId;
public AnimalKind(Context ctx, int imageId) {
super(ctx);
m_imageId = imageId;
super.setImageResource(imageId);
super.setAdjustViewBounds(true);
super.setScaleType(ImageView.ScaleType.FIT_XY);
super.setPadding(1, 1, 1, 1);
super.setBackgroundColor(Color.BLACK);
super.setOnClickListener(this);
}
//#Override
public void onClick(View v) {
//Do Something
}
#Override
public void setPressed(boolean pressed) {
//Do Something
}
public int getM_imageId() {
return m_imageId;
}
}
MY PREFERENCE ACTIVITY:
package com.KhalidSorensen.animalsounds;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.util.Log;
public class Preferences extends PreferenceActivity {
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
Log.i("Khalid", "Preferences: onCreate");
}
}
MY XML FOR MY MAIN ACTIVITY:
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<android.support.v4.view.PagerTitleStrip
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/lbl_title"
android:background="#33B5E5"
android:layout_gravity="top"
android:paddingTop="0dp"
android:paddingBottom="0dp"> "
</android.support.v4.view.PagerTitleStrip>
</android.support.v4.view.ViewPager>
AND FINALLY, MY XML FOR THE GRIDVIEW:
<?xml version="1.0" encoding="utf-8"?>
<GridView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/lbl_gridView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center_horizontal"
android:layout_margin="0px"
android:alwaysDrawnWithCache="false"
android:animateLayoutChanges="false"
android:background="#android:color/white"
android:columnWidth="130dp"
android:drawSelectorOnTop="true"
android:horizontalSpacing="#dimen/activity_horizontal_margin"
android:listSelector="#null"
android:numColumns="auto_fit"
android:padding="#dimen/activity_horizontal_margin"
android:scrollbarStyle="insideOverlay"
android:smoothScrollbar="true"
android:stretchMode="none"
android:verticalSpacing="#dimen/activity_vertical_margin" >
</GridView>

Use CENTER_INSIDE a scale type for your image view.
super.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
another thing that I would change is the way you handle the column width. I would remove the android:numColumns="auto_fit". On the other hand you know that the number of columns is the cealing of WidthViewGrid/desiderePicSize, where the most common case for WidthViewGrid is the screen's width. On then programmatically you can set number of columns of your GridView with setNumberOfColumns

I would say:
A. After calling setColumnWidth call the gridview.invalidate()
B. After returning from the change preference - call adapter's notifyDataSetChanged in order to make sure it re-creates the views in the adapter (i.e. getView will be called)

Related

How to change setText when i delete the data

I want to change my Button text when i delete the items
i already checked it getText, when i getText it shows that the data
already changed but when i try to setText, it's not show to me
In this case what shold i do?
This is my f_productAdapter
package com.example.together.Adapter;
import android.content.Context;
import android.media.Image;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.example.together.Model.FuneralProdcutOrder;
import com.example.together.R;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static com.example.together.Activities.EditProfileActivity.TAG;
public class f_productAdapter extends BaseAdapter {
Button b;
LayoutInflater inflater = null;
private ArrayList<FuneralProdcutOrder> list;
public f_productAdapter(ArrayList<FuneralProdcutOrder> f_order) {
super();
list = f_order;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public long getItemId(int position) {
return list.get(position).hashCode();
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if(convertView == null) {
inflater = (LayoutInflater) parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.item_funeralorder, parent, false);
}
TextView tv_name = convertView.findViewById(R.id.productnm); //상품이름
TextView tv_price = convertView.findViewById(R.id.productpri); //상품 가격
ImageView tv_img = convertView.findViewById(R.id.pro_img);
Button tv_delete = convertView.findViewById(R.id.deleteBtn);
FuneralProdcutOrder getProlist = list.get(position);
tv_name.setText(getProlist.getName());
tv_price.setText(getProlist.getPrice());
Picasso.get().load(getProlist.getImg()).fit().into(tv_img);
LayoutInflater inflaters = (LayoutInflater) parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View Toplayout = inflaters.inflate(R.layout.activity_goodbyepet_reservation_result, null );
//
b = Toplayout.findViewById(R.id.f_orderBtn);
TextView test = Toplayout.findViewById(R.id.toolbar_title);
Log.e("test",test.getText()+"");
// Log.e("view context", parent.getContext()+"");
// Log.e("view position", position+"");
// Log.e("view count", list.size()+"");
// Log.e("view",b.getText()+"");
// b.setText("테스트");
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.e("view alert" ,"확실히 버튼 객체를 찾았습니다 눌림");
}
});
tv_delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
list.remove(position);
b.setText("Show me~~~~ u r change!!!");
notifyDataSetChanged();
Log.d(TAG, "onClick: What is you?"+list.size());
}
});
return convertView;
}
}
This is my reservationResultActivity
package com.example.together.Activities.GoodbyePet;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.support.v7.widget.Toolbar;
import com.example.together.Adapter.f_productAdapter;
import com.example.together.Model.FuneralProdcutOrder;
import com.example.together.R;
import java.lang.reflect.Array;
import java.util.ArrayList;
public class GoodbyepetReservationResultActivity extends AppCompatActivity {
// private TextView tvParent, tvChild;
Toolbar myToolbar;
ListView funeralview;
Button Btn;
private ArrayList<FuneralProdcutOrder> f_order = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_goodbyepet_reservation_result);
int total_price = 0;
//리스트뷰선언
funeralview = findViewById(R.id.funeral_order);
//예약 버튼
Btn = findViewById(R.id.f_orderBtn);
//툴바 선언
myToolbar = findViewById(R.id.my_toolbar);
setSupportActionBar(myToolbar);
//액션바 왼쪽에 버튼
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_btn_back);
getSupportActionBar().setDisplayShowTitleEnabled(false);
for (int i = 0; i < MyCategoriesExpandableListAdapter.parentItems.size(); i++ ) {
for (int j = 0; j < MyCategoriesExpandableListAdapter.childItems.get(i).size(); j++ ){
String isChildChecked = MyCategoriesExpandableListAdapter.childItems.get(i).get(j).get(ConstantManager.Parameter.IS_CHECKED);
if (isChildChecked.equalsIgnoreCase(ConstantManager.CHECK_BOX_CHECKED_TRUE)) {
// tvParent.setText(tvParent.getText() + MyCategoriesExpandableListAdapter.childItems.get(i).get(j).get(ConstantManager.Parameter.SUB_CATEGORY_NAME));
// tvChild.setText(tvChild.getText() + MyCategoriesExpandableListAdapter.childItems.get(i).get(j).get(ConstantManager.Parameter.SUB_CATEGORY_PRICE));
String name = MyCategoriesExpandableListAdapter.childItems.get(i).get(j).get(ConstantManager.Parameter.SUB_CATEGORY_NAME);
String price = MyCategoriesExpandableListAdapter.childItems.get(i).get(j).get(ConstantManager.Parameter.SUB_CATEGORY_PRICE);
String img = MyCategoriesExpandableListAdapter.childItems.get(i).get(j).get(ConstantManager.Parameter.SUB_CATEGORY_IMAGE);
f_order.add(new FuneralProdcutOrder(name,price,img));
total_price = total_price + Integer.parseInt(price);
}
}
}
f_productAdapter orAdapter = new f_productAdapter(f_order);
// orAdapter.setHasStableId(true);
Log.e("view activiey", f_order.size()+"안녕");
funeralview.setAdapter(orAdapter);
Btn.setText(f_order.size()+"개 " + total_price+" 원 예약 신청하기");
Btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
//액션바 등록
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.alldelete_manu, menu) ;
return true ;
}
//액션바 클릭 이벤트
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// ((TextView)findViewById(R.id.textView)).setText("SEARCH") ;
return true;
case R.id.settings:
// ((TextView)findViewById(R.id.textView)).setText("ACCOUNT") ;
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
What i want to do
when i delete the button directly change buttons text also change
but setText() is not working
how to change that?
Click delete button
tv_delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
list.remove(position);
b.setText("Show me~~~~ u r change!!!");
notifyDataSetChanged();
Log.d(TAG, "onClick: What is you?"+list.size());
}
});
What i want to change the button text
Btn.setText(f_order.size()+"개 " + total_price+" 원 예약 신청하기");
This is my XML That include button what i want to change the text
<?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:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="fill_parent"
tools:context=".Activities.GoodbyePet.GoodbyepetReservationResultActivity">
<android.support.v7.widget.Toolbar
android:id="#+id/my_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/mdtp_white"
android:elevation="4dp"
android:theme="#style/ThemeOverlay.AppCompat.ActionBar">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="예약 상세서"
android:layout_gravity="center"
android:id="#+id/toolbar_title"
android:textSize="20sp"
/>
</android.support.v7.widget.Toolbar>
<ListView
android:id="#+id/funeral_order"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="0.3"
android:drawSelectorOnTop="false">
</ListView>
<Button
android:id="#+id/f_orderBtn"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="0.8"
android:layout_margin="10dp"
android:text="바뀌어주세요"
android:background="#drawable/button_radius"
android:textSize="18dp"/>
</LinearLayout>
Create an interface class like this;
You can set many kind of information as a parameter about your deleted item and send it to your activity.
public interface ItemSelectedListener{
void onItemSelected(boolean isDeleted);
}
In your adapter initialize your interface;
private List<ItemSelectedListener> mItemSelectedSubscribers = new ArrayList<ItemSelectedListener>();
Add this method in your adapter ;
public void subscribeItemSelection(ItemSelectedListener listener) {
mItemSelectedSubscribers .add(listener);
}
Set this loop in your click events;
tv_delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for (ItemSelectedListener listener : mItemSelectedSubscribers ) {
listener.onItemSelected(true);
}
list.remove(position);
b.setText("Show me~~~~ u r change!!!");
notifyDataSetChanged();
Log.d(TAG, "onClick: What is you?"+list.size());
}
});
In your activity, implement your interface and you will set a implemented methods. this methods look like this;
boolean isDeleted;
#Override
public void onItemSelected(boolean isDeleted) {
this.isDeleted = isDeleted;
}
You know now item is deleted or not. When a button deleted you can change text by using your method.
if(isDeleted){
btn.setText(changeText)
}
Hope this help!

Trying to get callbacks from DialogFragment to a fragment but the app is crashing

My app's MainActivity has a ViewPager which has three children(swipe views). When swiped to last child, the ActionBar gets two menu items. On clicking one item, a Dialog pops up to add a name of an item into a Database. On clicking second menu item, another Dialog pops up that prompts user to enter the name of the item that is to be removed from the Database. These Dialogs are getting constructed by separate Dialog Fragments. Basically what I want is to get the callback event from the Dialog that the positive or negative button has been clicked and wanna perform some action in the fragment which is as I mentioned is the last child of my ViewPager. I've seen the Android documentation as well as a Youtube video to learn how to implement the interface, yet my app's crashing.
Here's the code for my DialogFragment which shows a Dialog that prompts the user to enter input and save it to the Database.
package com.example.android.mybusiness;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class AddCigaretteNameDialog extends DialogFragment {
EditText userInput;
String cigaretteName;
DbHelper dbHelper;
public AddCigaretteNameDialogListener listener;
public interface AddCigaretteNameDialogListener {
void onDialogPositiveClick(String name);
}
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
dbHelper = new DbHelper(getContext());
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// SET THE TITLE FOR THE DIALOG.
builder.setTitle(R.string.add_title);
// GET THE LAYOUT INFLATOR
LayoutInflater inflater = getActivity().getLayoutInflater();
// INFLATE THE LAYOUT AND PUT IT INTO A VARIABLE.
// PASS NULL AS PARENT VIEW, BECAUSE IT'S GOING IN THE DIALOG
View view = inflater.inflate(R.layout.edit_text_for_dialogs, null);
// GET THE EDIT_TEXT FROM THE 'VIEW' VARIABLE.
userInput = view.findViewById(R.id.cigarette_name_user_input);
// SET THE LAYOUT FOR THE DIALOG
builder.setView(view);
// SET ACTION BUTTONS
builder.setPositiveButton(R.string.save, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
// GET THE USER INPUT FROM THE EDIT_TEXT ABOVE AND PUT IT INTO A VARIABLE.
cigaretteName = userInput.getText().toString();
// PUT THE USER INPUT IN THE DATABASE.
Boolean result = dbHelper.insertCigaretteName(cigaretteName);
if (result) {
// SHOW SUCCESS MESSAGE THAT CIGARETTE NAME HAS BEEN INSERTED.
Toast.makeText(getContext(), cigaretteName + " has been added successfully!", Toast.LENGTH_SHORT).show();
listener.onDialogPositiveClick(cigaretteName);
} else {Toast.makeText(getContext(), "Something is wrong", Toast.LENGTH_SHORT).show();}
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dismiss();
}
});
// RETURN THE DIALOG.
return builder.create();
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
// VERIFY THAT THE HOST ACTIVITY IMPLEMENTS THE CALLBACK INTERFACE
try {
listener = (AddCigaretteNameDialogListener) getTargetFragment();
} catch (ClassCastException e){
// THE ACTIVITY DOESN'T IMPLEMENT INTERFACE, THROW AN EXCEPTION.
throw new ClassCastException(getActivity().toString() + " must implement listener");
}
}
}
And here's the fragment which is the last child of the view pager.
package com.example.android.mybusiness;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
/**
* A simple {#link Fragment} subclass.
*/
public class Purchase extends Fragment implements AddCigaretteNameDialog.AddCigaretteNameDialogListener {
Spinner spinner;
DbHelper dbHelper;
ArrayAdapter<String> arrayAdapter;
// FRAGMENT'S CONSTRUCTOR.
public Purchase() { }
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// KIND OF REQUIREMENT FOR OPTION MENUS.
setHasOptionsMenu(true);
// INSTANTIATING THE OBJECT TO RUN A FUNCTION, WHICH GETS THE CIGARETTES NAME.
dbHelper = new DbHelper(getContext());
// Inflate the layout for this fragment
// AND PUT IT INTO A VARIABLE SO WIDGETS CAN BE ACCESSED.
View view = inflater.inflate(R.layout.fragment_purchase, container, false);
// FIND THE spinner.
spinner = view.findViewById(R.id.spinner);
// CREATING THIS ADAPTER TO POPULATE THE SPINNER WIDGET.
arrayAdapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_list_item_1, dbHelper.getAllCigaretteNames());
// SETTING THE ADAPTER TO THE SPINNER, WHICH WILL PROVIDE THE CONTENT TO BE SELECTED BY ME.
spinner.setAdapter(arrayAdapter);
return view;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu, menu);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.add_cigarette:
AddCigaretteNameDialog addCigaretteNameDialog = new AddCigaretteNameDialog();
addCigaretteNameDialog.show(getFragmentManager(), "add_cigarette_name");
return true;
case R.id.remove_cigarette:
RemoveCigaretteNameDailog RemoveCigaretteNameDailog = new RemoveCigaretteNameDailog();
RemoveCigaretteNameDailog.show(getFragmentManager(), "add_cigarette_name");
; return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onDialogPositiveClick(String name) {
arrayAdapter.add(name);
}
}
Here's the crash log:
12-07 13:13:59.278 25327-25327/com.example.android.mybusiness
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.android.mybusiness, PID: 25327
java.lang.NullPointerException: Attempt to invoke interface method 'void
com.example.android.mybusiness.AddCigaretteNameDialog$AddCigaretteNameDialogListener.onDialogPositiveClick(java.lang.String)'
on a null object reference
at com.example.android.mybusiness.AddCigaretteNameDialog$2.onClick(AddCigaretteNameDialog.java:58)
at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:162)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5296)
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:912)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:707)
Line 58 is
listener.onDialogPositiveClick(cigaretteName);
Thanks in advance!
If you use custom dialog class with custom view this would solve your problem. I am posting a code below which shows a custom dialog with views. first of all create a layout file for your dialog design by name dlg_add_cigarette_name inside layout folder
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:background="#drawable/dialog_background_inset"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_marginLeft="16dp"
android:text="Cigrate Name:"
android:id="#+id/tv_label_total"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/layout_total_update"
android:orientation="horizontal"
android:layout_below="#+id/tv_label_total"
android:weightSum="2"
>
<EditText
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1.5"
android:layout_marginLeft="16dp"
android:layout_marginRight="10dp"
android:id="#+id/et_cgrate_name"
android:inputType="text"
/>
</LinearLayout>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/layout_total_update"
android:layout_alignParentRight="true"
android:background="#android:color/transparent"
android:layout_marginRight="70dp"
android:text="OK"
android:layout_marginBottom="20dp"
android:layout_marginTop="20dp"
android:id="#+id/button_ok"
android:textColor="#color/colorPrimaryDark"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/layout_total_update"
android:layout_toLeftOf="#+id/button_ok"
android:layout_marginRight="30dp"
android:text="Cancel"
android:layout_marginBottom="20dp"
android:layout_marginTop="20dp"
android:background="#android:color/transparent"
android:id="#+id/button_cancel"
android:textColor="#color/colorPrimaryDark"
/>
Now inside drawable folder create a new file by name dialog_background_insetand update the file by following code
<?xml version="1.0" encoding="utf-8"?>
<inset
xmlns:android="http://schemas.android.com/apk/res/android"
android:drawable="#color/white"
android:insetRight="15dp"
android:insetLeft="15dp">
</inset>
and now in your AddCigaretteNameDialog file update the class by following code
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.drinkwater.reminder.watertracker.R;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
public class AddCigaretteNameDialog extends DialogFragment {
private static final float DIM_AMOUNT = 0.4f;
#BindView(R.id.tv_label_total)
TextView tvLabelTotal;
#BindView(R.id.et_cgrate_name)
EditText etCgrateName;
#BindView(R.id.layout_total_update)
LinearLayout layoutTotalUpdate;
#BindView(R.id.button_ok)
Button buttonOk;
#BindView(R.id.button_cancel)
Button buttonCancel;
#OnClick(R.id.button_cancel)
public void onClick(){
dismiss();
}
#OnClick(R.id.button_ok)
public void onClickOkay(){
unitCallBack.addCigarette(cigaretteName);
}
private Unbinder mUnbinder;
private AddCigaretteName unitCallBack;
private String cigaretteName;
public AddCigaretteNameDialog() {
}
public static AddCigaretteNameDialog newInstance(String title) {
AddCigaretteNameDialog frag = new AddCigaretteNameDialog();
Bundle args = new Bundle();
args.putString("title", title);
frag.setArguments(args);
return frag;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (unitCallBack == null && context instanceof AddCigaretteName) {
unitCallBack = (AddCigaretteName) context;
}
}
#Override
public void onDetach() {
super.onDetach();
unitCallBack = null;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Dialog dialog = super.onCreateDialog(savedInstanceState);
final Window window = dialog.getWindow();
if (window != null) {
window.requestFeature(Window.FEATURE_NO_TITLE);
window.setBackgroundDrawableResource(android.R.color.transparent);
WindowManager.LayoutParams windowLayoutParams = window.getAttributes();
windowLayoutParams.dimAmount = DIM_AMOUNT;
}
dialog.setCancelable(false);
dialog.setCanceledOnTouchOutside(false);
return dialog;
}
#SuppressLint("NewApi")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.test, container, false);
mUnbinder = ButterKnife.bind(this, view);
etCgrateName.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
cigaretteName=s.toString();
}
#Override
public void afterTextChanged(Editable s) {
}
});
return view;
}
#Override
public void onResume() {
super.onResume();
final int width = getScreenWidth();
int height = getScreenHeight() / 2;
changeWindowSizes(width, ViewGroup.LayoutParams.WRAP_CONTENT);
}
private void changeWindowSizes(int width, int height) {
final Window window = getDialog().getWindow();
if (window != null) {
window.setLayout(width, height);
}
}
#Override
public void onDestroyView() {
super.onDestroyView();
mUnbinder.unbind();
}
#Override
public int getTheme() {
return R.style.CustomDialog;
}
public interface AddCigaretteName {
void addCigarette(String name);
}
public static int getScreenWidth() {
return Resources.getSystem().getDisplayMetrics().widthPixels;
}
public static int getScreenHeight() {
return Resources.getSystem().getDisplayMetrics().heightPixels;
}
}
create a custom theme inside styles file
<style name="CustomDialog" parent="Theme.AppCompat.Light.Dialog">
<item name="android:windowAnimationStyle">#style/CustomDialogAnimation</item>
</style>
<style name="CustomDialogAnimation">
<item name="android:windowEnterAnimation">#anim/translate_left_side</item>
<item name="android:windowExitAnimation">#anim/translate_right_side</item>
</style>
create a package anim inside resfolder and create two files translate_left_sideand translate_right_side
translate_right_side
<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromXDelta="0%" android:toXDelta="100%"
android:fromYDelta="0%" android:toYDelta="0%"
android:duration="600"/>
translate_left_side
<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="600"
android:fromXDelta="100%"
android:toXDelta="0%"/>
Your AddCigrateDialog is ready to appear.Now its time to call this dialog from button click.Inside Purchase make an object of AddCigaretteDialog class globally
AddCigaretteNameDialog addCigaretteNameDialog;
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.add_cigarette:
addCigaretteNameDialog= new AddCigaretteNameDialog();
addCigaretteNameDialog= AddCigaretteNameDialog.newInstance("AddCigrateNameDialog");
addCigaretteNameDialog.show(manager,"show");
return true;
case R.id.remove_cigarette:
RemoveCigaretteNameDailog RemoveCigaretteNameDailog = new RemoveCigaretteNameDailog();
RemoveCigaretteNameDailog.show(getFragmentManager(), "add_cigarette_name");
; return true;
default:
return super.onOptionsItemSelected(item);
}
}
And yes don't forget to implement the interface of AddCigaretteDialog inside Purchase dialog
As I am using ButterKnife dependency add the following lines inside your app's gradle file
inal BUTTER_KNIFE_VERSION = "8.8.1"
implementation "com.jakewharton:butterknife:$BUTTER_KNIFE_VERSION"
annotationProcessor "com.jakewharton:butterknife-compiler:$BUTTER_KNIFE_VERSION"

Image slider moving fast in android when comeback from another activity

In my android app I have an image slider using viewpager,which changes images every 2.5 seconds in the main activity,it works fine when I open the app,but the problem is when I jump to another Activity from the MainActivity and come back it,starts to move the images in the slides very fast,as much as I jump to another activity the sliding become more faster.please help.
This is where I have included my 3 slider images
slidelist.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView
android:id="#+id/image1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:adjustViewBounds="true"
android:layout_gravity="center"
android:src="#drawable/slidetwo"
android:scaleType="centerCrop"/>
<ImageView
android:id="#+id/image2"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:adjustViewBounds="true"
android:layout_gravity="center"
android:src="#drawable/slideone"
android:scaleType="centerCrop"/>
<ImageView
android:id="#+id/image3"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:adjustViewBounds="true"
android:layout_gravity="center"
android:src="#drawable/slidethree"
android:scaleType="centerCrop"/>
</FrameLayout>
This the slider layout in content main.xml(included in activity)
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="250dp"
android:layout_below="#+id/linearone">
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentTop="true" />
<me.relex.circleindicator.CircleIndicator
android:id="#+id/indicator"
android:layout_width="match_parent"
android:layout_height="48dp"
android:layout_alignParentBottom="true"/>
</RelativeLayout>
The following is the adpater class
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.example.rimapps.icar_iisr_turmeric.R;
import java.util.ArrayList;
public class SlideAdapter extends PagerAdapter {
private ArrayList<Integer> images;
private LayoutInflater inflater;
private Context context;
public SlideAdapter(Context context, ArrayList<Integer> images) {
this.context = context;
this.images=images;
inflater = LayoutInflater.from(context);
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
#Override
public int getCount() {
return images.size();
}
#Override
public Object instantiateItem(ViewGroup view, int position) {
View myImageLayout = inflater.inflate(R.layout.slidelist, view, false);
ImageView myImage1 = (ImageView) myImageLayout.findViewById(R.id.image1);
ImageView myImage2 = (ImageView) myImageLayout.findViewById(R.id.image2);
ImageView myImage3 = (ImageView) myImageLayout.findViewById(R.id.image3);
myImage1.setImageResource(images.get(position));
myImage2.setImageResource(images.get(position));
myImage3.setImageResource(images.get(position));
view.addView(myImageLayout, 0);
return myImageLayout;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view.equals(object);
}
}
This is my MainActivity class and here I have defined the timer for the slider
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.internal.NavigationMenuItemView;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import com.example.rimapps.icar_iisr_turmeric.R;
import com.example.rimapps.icar_iisr_turmeric.control.ButtonAdapter;
import com.example.rimapps.icar_iisr_turmeric.control.SlideAdapter;
import com.example.rimapps.icar_iisr_turmeric.model.ContentsDep;
import com.example.rimapps.icar_iisr_turmeric.utils.LocaleHelper;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import me.relex.circleindicator.CircleIndicator;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
CircleIndicator indicator;
int period=2500, delay = 2500;
private static ViewPager mPager;
private static int currentPage = 0;
private static final Integer[] slide = {R.drawable.slideone, R.drawable.slidetwo, R.drawable.slidethree};
private ArrayList<Integer> slidearray = new ArrayList<Integer>();
Timer swipeTimer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
//Image slider function//
private void init() {
for (int i = 0; i < slide.length; i++)
slidearray.add(slide[i]);
mPager = (ViewPager) findViewById(R.id.pager);
mPager.setAdapter(new SlideAdapter(MainActivity.this, slidearray));
CircleIndicator indicator = (CircleIndicator) findViewById(R.id.indicator);
indicator.setViewPager(mPager);
// Auto start of viewpager
final Handler handler = new Handler();
final Runnable Update = new Runnable() {
public void run() {
if (currentPage == slide.length) {
currentPage = 0;
}
mPager.setCurrentItem(currentPage++, true);
}
};
swipeTimer =new Timer();
swipeTimer.schedule(new
TimerTask() {
#Override
public void run () {
Log.d("hjgv","yughi");
handler.post(Update);
}
},delay,period);
}
#Override
protected void onStop() {
super.onStop();
// swipeTimer.cancel();
delay=0;
period=0;
}
#Override
protected void onRestart() {
super.onRestart();
delay=2500;
period=2500;
}
}
The problem is in your Timer.
when you go another fragment or activity then back to that fragment you must have to cancel your timer ondestroyview because when you back to fragment your oncreateview is call again so timer are initialise and then speed is multiple by 2 time.this happens everytime.
This code in kotlin.
override fun onDestroyView() {
if(swipeTimer != null) {
swipeTimer.cancel()
}
super.onDestroyView()
}
Hope this help you
Just call cancel the instance of Timer in your ondestryView() method
#Override
public void onDestroyView() {
super.onDestroyView();
if(swipeTimer != null) {
swipeTimer.cancel();
}
}

Android ListView in a ListFragment

I am trying to implement a simple ListView into a Fragment. I have seen many tutorials on how to do so but for some reason my adaptation does not work and I cannot figure out why.
the goal: to have a fragment with one listview.
I understand there are many questions about this and I have seen most of them but mine does not work and I have tried many variations with no success.
From what I have gathered ListFragment and AppCompatActivity are the most appropiate:
//code for fragment.
package com.example.student.hwapp;
import android.support.v4.app.ListFragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
public class TasksFragment extends ListFragment {
public TasksFragment(){}
public String[] list = {"1","2","3","4","5","6"};
ListAdapter theAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View rootView = inflater.inflate(R.layout.tasks_fragment,container,false);
theAdapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1, list);
setListAdapter(theAdapter);
return rootView;
}
public static TasksFragment newInstance() {
TasksFragment fragment = new TasksFragment();
return fragment;
}
}
the XML for tasks_fragment (as you can see the list id is list) :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent" android:layout_height="match_parent">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/list"
tools:listitem="#android:layout/simple_list_item_2"
android:choiceMode="multipleChoice"
android:footerDividersEnabled="false"
android:clickable="false" />
</RelativeLayout>
and finally the Activity that holds the fragment:
package com.example.student.hwapp;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MainMenu extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_menu);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch(position){
case 0:
return TasksFragment.newInstance();
case 1:
return ClassFragment.newInstance();
}
return null;
}
#Override
public int getCount() {
// Show 2 total pages.
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "SECTION 1";
case 1:
return "SECTION 2";
}
return null;
}
}
When I test the TasksFragment as a normal activity, it actually works but when I make it a fragment it doesn't.
Thank you for your help, sorry for the very specific and repetitive question but I really could not find a solution, I'm probably missing something very simple.
EDIT:
14203/com.example.student.hwapp E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'
But I DO have a ListView and its id IS list as I showed in the code.
Your android:id="#+id/list" is not the same as what is being asked for in the error message, which is android:id="#android:id/list". The former is YOUR object; Android needs its OWN object. Refer to this, among many others.

Android Picasso Fragment Pic from URL

I've got problem to load pic from URL do my fragment by Picasso.
When I start app it's start without any errors but pic is not loading.
My app has one MainActivity and three fragments. Below I paste xml of mainlayout and one fragment class. The best for me is this scenario:
when user click button on fragment three(red on image), pic will load from url to imageView which is located on fragment two (yellow on image) above of fragment three.
Please help
package testowy.com.testowyfragment2;
import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import com.squareup.picasso.Picasso;
/**
* Created by Administrator on 2015-07-04.
*/
public class Klasadown extends Fragment {
private klasadownlistener listener;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragmentdown, container, false);
ImageView img = (ImageView) view.findViewById(R.id.imgVV);
Context c = getActivity().getApplicationContext();
Picasso.with(c).load("http://inthecheesefactory.com/uploads/source/glidepicasso/cover.jpg")
.fit().into(img);
View.OnClickListener clickListener = new View.OnClickListener() {
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnMenu:
updateText("Menu");
SetImage();
break;
case R.id.btnKontakt:
updateText("Kontakt");
break;
default:
break;
}
}
};
Button btnMenu = (Button) view.findViewById(R.id.btnMenu);
Button btnKontakt = (Button) view.findViewById(R.id.btnKontakt);
btnKontakt.setOnClickListener(clickListener);
btnMenu.setOnClickListener(clickListener);
return view;
}
public interface klasadownlistener {
public void onItemSelected(String txt);
}
private void updateText(String txt) {
listener.onItemSelected(txt);
}
public void SetImage() {
ImageView img = (ImageView) getView().findViewById(R.id.imgVV);
Picasso.with(getActivity().getApplicationContext()).load("http://inthecheesefactory.com/uploads/source/glidepicasso/cover.jpg").into(img);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (activity instanceof klasadownlistener) {
listener = (klasadownlistener) activity;
} else {
throw new ClassCastException(activity.toString() + " musi implementowa� interfejs: OverviewFragment.OverviewFragmentActivityListener");
}
}
}
<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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity">
<fragment
android:id="#+id/fragmentup"
class="testowy.com.testowyfragment2.Klasaup"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="5">
</fragment>
<fragment
android:id="#+id/fragmentcenter"
class="testowy.com.testowyfragment2.Klasacenter"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="3">
</fragment>
<fragment
android:id="#+id/fragmetdown"
class="testowy.com.testowyfragment2.Klasadown"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="3">
</fragment>
</LinearLayout>
package testowy.com.testowyfragment2;
import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
/**
* Created by Administrator on 2015-07-04.
*/
public class Klasacenter extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater
.inflate(R.layout.fragmentcenter, container, false);
return view;
}
public void SetText(String txt){
TextView view = (TextView) getView().findViewById(R.id.fragmentcenterText);
view.setText(txt);
}
}
package testowy.com.testowyfragment2;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ImageView;
import com.squareup.picasso.Picasso;
public class MainActivity extends Activity implements Klasadown.klasadownlistener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public void onItemSelected(String txt) {
Klasacenter fragment = (Klasacenter) getFragmentManager()
.findFragmentById(R.id.fragmentcenter);
// sprawdzamy czy fragment istnieje w tej aktywno�ci
if (fragment != null && fragment.isInLayout()) {
// ustawiamy teskt we fragmencie
fragment.SetText(txt);
ImageView img = (ImageView) findViewById(R.id.imgV);
Picasso.with(this).load("http://inthecheesefactory.com/uploads/source/glidepicasso/cover.jpg").fit().into(img);
}
}
}
It's stupid to say but I forget to add internet permission:)
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
now everything is ok!

Categories

Resources